在下面的函数中,即使我知道数据库中有几项要添加,addToFlatList也仅被调用一次。似乎拳头addToFlatList从未解决?我究竟做错了什么?

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


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"});
    });
}


更新:

试图像这样返回调度。 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"});
        });
    }
}


还尝试了这个:

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"});
    });
}

最佳答案

您必须退还诺言:

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"});
    });
};


或者,您必须等待promise,以便您的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"});
    }
}

10-01 17:30