Async/Await-操作顺序不起作用



概述

我正在一个使用redux的react应用程序中工作。我有一个行动,检查我们是否有新的图像数据。如果是,它将上传它,接收新的URL,然后使用这些数据更新对象。

问题

但是,我的函数中的操作顺序按预期进行,但是函数外的代码在完成之前就运行了。

问题

为什么底部的控制台日志在异步函数的内容完成之前执行?

if(imageData) {
const imageGUID = guid();
const storageRef = projectStorage.ref(`${imageData.name}_${imageGUID}`);
// This function should complete before the console log at the bottom is called.
await storageRef.put(imageData).on('state_changed', snap => {
}, async (err) => {
console.log(err)
toastr.error("Uh Oh!", `Could not upload image`);
}, async () => {
imageURL = await storageRef.getDownloadURL();
console.log("NEW IMAGE URL: ", imageURL);

})
}
console.log("Done setting up new image: ", imageURL) // This is called before we get the IMAGE URL from Firestore.... why?

.on函数不返回Promise,因此没有什么可以等待await。您必须将put的事件基础API转换为Promise。


if (imageData) {
const imageGUID = guid();
const storageRef = projectStorage.ref(`${imageData.name}_${imageGUID}`);
// This function should complete before the console log at the bottom is called.
try {
await new Promise((resolve, reject) => {
storageRef.put(imageData)
.on('state_changed', snap => {},
reject, resolve)
})
imageURL = await storageRef.getDownloadURL();
console.log("NEW IMAGE URL: ", imageURL);
} catch (err) {
console.log(err)
toastr.error("Uh Oh!", `Could not upload image`);
}
}
console.log("Done setting up new image: ", imageURL)

storageRef.put(imageData).on-看起来不像promise(您在回调中上传图像(,所以await没有意义

如果你想使用承诺,你应该写一些类似的东西

await new Promise((resolve, reject) => {
storageRef
.put(imageData)
.on('state_changed', snap => {
}, async (err) => {
console.log(err);
toastr.error('Uh Oh!', `Could not upload image`);
reject()
}, async () => {
imageURL = await storageRef.getDownloadURL();
console.log('NEW IMAGE URL: ', imageURL);
resolve()
});
})

最新更新