简体   繁体   English

异步/等待功能永远不会用 Dispatch 解决

[英]Async/Await function is never resolved with Dispatch

In my function below, addToFlatList is only called once, even though I know there are several items in my database to be added.在我下面的函数中, addToFlatList只被调用一次,即使我知道我的数据库中有几个项目要添加。 Seems like the fist addToFlatList is never resolved?似乎拳头addToFlatList从未解决过? What am I doing wrong?我究竟做错了什么?

photosSnapshot.forEach(async function(childSnapshot) {
    await addToFlatList(childSnapshot.key, childSnapshot.val())(dispatch);
});

addToFlatList function: addToFlatList 函数:

const addToFlatList = (photoId, photoObj) => async(dispatch) => { 
    database.ref('users').child(photoObj.author).once('value').then((userSnapshot) => {
        var userInfo = userSnapshot.val();
        dispatch({type: "GOT_USER", payload: userInfo});
    }).catch(error => {
        dispatch({type: "GOT_ERROR"});
    });
}

Update :更新

Tried to return dispatch like this.试图像这样返回调度。 addToFlatList is still only called once. addToFlatList仍然只调用一次。

const addToFlatList = async(photoId, photoObj) => {
    return (dispatch) => { 
        database.ref('users').child(photoObj.author).once('value').then((userSnapshot) => {
            var userInfo = userSnapshot.val();
            dispatch({type: "GOT_USER", payload: userInfo});
        }).catch(error => {
            dispatch({type: "GOT_ERROR"});
        });
    }
}

Also tried this:也试过这个:

const addToFlatList = async(photoId, photoObj) => {
    database.ref('users').child(photoObj.author).once('value').then((userSnapshot) => {
        return (dispatch) => { 
          // never hit this point
          var userInfo = userSnapshot.val();
          dispatch({type: "GOT_USER", payload: userInfo});
        }
    }).catch(error => {
        dispatch({type: "GOT_ERROR"});
    });
}

You must return the promise:您必须返回承诺:

const addToFlatList = (photoId, photoObj) => (dispatch) => { 
    return database.ref('users').child(photoObj.author).once('value').then((userSnapshot) => {
//  ^^^^^^
        var userInfo = userSnapshot.val();
        return dispatch({type: "GOT_USER", payload: userInfo});
    }).catch(error => {
        return dispatch({type: "GOT_ERROR"});
    });
};

Alternatively, you must await the promise so that your async function doesn't end prematurely:或者,您必须等待承诺,以便您的async功能不会过早结束:

const addToFlatList = (photoId, photoObj) => async (dispatch) => { 
    try {
        const userSnapshot = await database.ref('users').child(photoObj.author).once('value');
//                           ^^^^^
        var userInfo = userSnapshot.val();
        return dispatch({type: "GOT_USER", payload: userInfo});
    } catch(error) {
        return dispatch({type: "GOT_ERROR"});
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM