【发布时间】:2021-05-26 20:16:55
【问题描述】:
我正在根据来自 API 的两个不同请求构建一个对象。在任何给定时间,这些请求都会使用三个不同的ids。例如const ids = [1, 2, 3]
整个代码都在 useEffect 中,因为我希望它在每次 ids 更改时运行。不确定这是否会影响代码执行顺序。
我希望我的程序按以下顺序运行:
- 首先,我想运行请求以获取每个 ID 的“general_info”并将它们添加到对象中。
- 其次,我想运行将每个 id 与其余 id 分别进行比较并将此信息添加到对象的请求。
- 第三,我想仅在上述代码完成“合并”此对象后运行一些代码。这就是我使用 React 的 UseState 挂钩将 objCopy 设置为将要显示的对象的地方!
我很欣赏这应该处理异步请求,根据其他帖子,某些类型的循环似乎不适合这个。我不确定是使用async await 还是简单地链接then() 一个接一个。
代码类似这样:
useEffect(() => {
// ... some other code ...
const obj = {}
// 1st loop
ids.forEach(id =>{
fetch(`api/general_info?id=${id}`)
//whatever comes as response, merge into 'obj'
})
// 2nd loop (to be run only after first loop has finished merging into obj)
idsToCompare = [[1, 2], [1, 3], [2, 3]] //
idsToCompare.forEach(([id1, id2]) =>{
fetch(`api/compare/?id1=${id1}&id2=${id2}`)
//whatever comes as response, merge into 'obj'
})
// 3 run this code ONLY AFTER the above loops have finished executing
// (and obj merge is complete)!
setCompleteObjToDisplay(obj) // React's setState
console.log(obj) // complete obj!
}, [ids]) //every time ids change, this code should run.
【问题讨论】:
标签: javascript reactjs async-await fetch use-effect