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