繁体   English   中英

为什么等待承诺不等待承诺解决?

[英]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后缀。

编辑

异步逻辑的 Stackblitz 示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM