gpt4 book ai didi

javascript - 异步/等待功能永远不会通过 Dispatch 解决

转载 作者:行者123 更新时间:2023-11-29 20:40:29 25 4
gpt4 key购买 nike

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

最佳答案

您必须返回 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"});
});
};

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

关于javascript - 异步/等待功能永远不会通过 Dispatch 解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55676990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com