概述
我正在使用 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?
uj5u.com熱心網友回復:
該.on函式不回傳 Promise,因此無需等待await. 您必須將事件基礎 API 轉換put為 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)
uj5u.com熱心網友回復:
storageRef.put(imageData).on- 看起來不像承諾(你在回呼中上傳你的圖片),所以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()
});
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/367826.html
標籤:javascript 反应 异步等待
上一篇:通過點擊按鈕反應鉤子
