【发布时间】:2021-07-06 21:46:03
【问题描述】:
正如我的代码 sn-p 之间的 cmets 中所述,异步未按预期工作。对于每个id,应该返回一个对象/项目,但它只返回一个项目,因为我的async await 没有正确实现。有什么可能的解决方法?
提前致谢
useEffect(() => {
axios.get('url-here').then((res) => {
res.data.favProperties?.map((el) => {
console.log(el) // this returns multitple id's of saved/liked items
axios.get('url-here').then(async (r) => {
if (r.data) {
console.log(r.data) // Problem starts here
// This returns the full object of the liked items
// But only one object is returned, not every object for which an id was stored
await storageRef
.child(r.data.firebaseRef + '/' + r.data.images[0])
.getDownloadURL()
.then((url) => {
// Here i need to fetch the image for each object
console.log(url)
})
.catch((err) => console.log(err))
}
})
})
})
}, [])
【问题讨论】:
-
这似乎是在 useEffect 钩子中调用的奇怪代码,也许包含组件的更多细节将有助于定义您要执行的操作。
-
除了上面@ScottGnile 所说的内容之外,您可能应该使用
async/await,因为这会提高代码的易读性,从而增加维护和错误修复。 -
嗯,我正在使用
async await并尝试了很多不同的东西,但没有任何效果。我怎样才能正确地实现async await? -
@ScottGnile 我应该在哪里以及如何拨打电话?
-
@brunelli 您可以在此处阅读有关如何将代码迁移到异步/等待的信息stackoverflow.com/a/55272812/1816108
标签: reactjs asynchronous async-await axios