调度永远无法解决异步/等待功能

时间:2019-04-14 15:31:08

标签: javascript ecmascript-6 async-await es6-promise dispatch

在下面的函数中,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"});
    });
}

1 个答案:

答案 0 :(得分:2)

您必须兑现承诺:

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

或者,您必须等待诺言,以使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"});
    }
}