![](/img/trans.png)
[英]JS async/await doesn't wait for my functions to resolve their promise
[英]Why await a promise doesn't wait the promise to resolve?
我正在嘗試學習正確使用異步等待,但我對此感到有些困惑。
在片段中,我試圖構建一個對象數組,其中包含我需要的有關我在組件中上傳的文件的信息。 問題是 this.fileInfo 中的對象並沒有完全等待返回編碼圖像的承諾,在我 console.log this.fileInfo 時返回此輸出:
如您所見,關鍵圖像是一個值未定義的 ZoneAwarePromise。 你能幫我解決這個問題嗎?
函數構建()
async build(e) {
let files = e.target.files;
this.j = Array.from(files);
this.fileInfo = await this.j.reduce((acc, cur) => [
...acc, {
name: cur.name.replace(/^.*\\/, ""),
sizeunit: this.getSize(cur.size),
extention: cur.name.split(/\.(?=[^\.]+$)/).slice(-1).pop().toString(),
image: this.previewFile(cur)
}
], [])
console.log(await this.fileInfo);
}
承諾
async previewFile(file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
return new Promise((res) => {
res(reader.result)
}).then( res => res);
};
}
您沒有在此函數中等待任何內容: async previewFile(file)
。 也許你假設在你的代碼行的某個地方返回一個新的 Promise 會使它作為一個 Promise 起作用。 在這種特殊情況下,它將不起作用,因為它位於委托 (onload) 內,不會在您的函數previewFile()
的范圍內執行。
你可以失去 async 修飾符,因為你可以返回一個 Promise 來代替:
previewFileAsync(file) {
// the async modifier keyword is not necessary,
// because we don't need to await anything.
return new Promise((res) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => res(reader.result);
});
}
當您調用它時,您可以在循環中等待它:
async buildAsync(e) {
let files = e.target.files;
for(let i = 0; i < files.length; i++) {
const file = files[i];
const preview = await previewFileAsync(file);
// Do something with preview here...
}
}
當然,您可以執行一系列 promise 以允許某種並發性,但這將有助於您入門。
我在您的方法中添加了Async
后綴,以便調用者知道可以等待。 它沒有做任何特別的事情,但它有助於澄清您的代碼。 您可以使用您認為正確的任何后綴。 我只是習慣了Async
后綴。
編輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.