【发布时间】:2022-11-28 00:05:23
【问题描述】:
在我的 React 应用程序的上下文文件中,我有以下功能:
const fetchAll = (userId) => {
try {
fetchDetails(userId)
// To be clear... There's multiple functions here, i.e:
// fetchContact(userId)
} catch (err) {
console.log(err)
}
setPending(false)
}
我已经删除了一些功能 - 但该功能的主要前提是将多个承诺组合在一起,并且在这些完成之前,显示一个“待定”组件。
如果“待定”状态设置为 true,则会显示此待定组件:
const [pending, setPending] = useState(true)
但是,目前发生的情况是尝试尝试,但同时执行了 setPending。
我认为解决这个问题的一种方法是在我的 try/catch 结束时使用“finally”调用,但它仍然同时执行。像这样:
const fetchAll = (userId) => {
try {
fetchDetails(userId)
} catch (err) {
console.log(err)
} finally {
setPending(false)
}
}
我不希望我的任何函数异步运行:我希望它们全部同时执行,以防止同时出现多个网络请求的瀑布效应。
作为参考,我个人的“获取”函数调用端点并根据响应设置状态数据:
const fetchDetails = (userId) => {
axios.post("/api/fetch/fetchDetails", {
id: userId
})
.then((response) => {
console.log(response.data)
setName(response.data.name)
setPreviewPhoto(response.data.profile_picture_url)
setPhotoName(response.data.profile_picture_name)
setPhotoFile(response.data.profile_picture_url)
})
}
有没有人对我如何使这项工作有任何建议?
【问题讨论】:
标签: reactjs