为什么等待诺言不等待诺言解决? [英] Why await a promise doesn't wait the promise to resolve?

查看:67
本文介绍了为什么等待诺言不等待诺言解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习正确使用异步等待,但是对此我感到有些困惑.

I am trying to learn to use properly async await but I am kind of cofused about it.

在代码片段中,我正在尝试构建一个对象数组,其中包含我要在组件中上传的文件所需的信息.问题是this.fileInfo中的对象没有完全等待诺言返回编码的图像,而是在我console.log this.fileInfo:

In the snippets, I am trying to build an array of object containing the infos I need about the file I am uploading in the component. The problem is that the objects in this.fileInfo are not exactly waiting the promise to return the encoded images, returning this output as I console.log this.fileInfo:

如您所见,关键图像是一个ZoneAwarePromise,其值未定义.你能帮我解决这个问题吗?

As you can see, the key image is a ZoneAwarePromise whose value is undefined. Can you please help me to fix this?

函数build()

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的作用.在这种特殊情况下,它将不起作用,因为它位于委托(加载)内部,不会在函数 previewFile()的范围内执行.

You are not awaiting anything in this function: async previewFile(file). Perhaps you assume returning a new Promise somewhere along the lines of your code will make it function as a Promise. In this particular case it will not work, because it is inside a delegate (onload), that will not be executed within the scope of your function previewFile().

您可能会丢失async修饰符,因为您可以改为返回Promise:

You can lose the async modifier, because you can return a Promise instead:

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);
    });
}

调用此函数时,可以在循环中等待它:

When you call this, you can await it inside your loop:

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,以实现某种程度的并发,但这将帮助您入门.

Of course, you can execute a range of promises to allow for some sort of concurrency, but this will help get you started.

我在您的方法中添加了 Async 后缀,以便调用者知道可以等待它.它没有做任何特殊的事情,但是它有助于澄清您的代码.您可以使用任何您认为正确的后缀.我只是习惯了 Async 后缀.

I added the Async suffix to your method so a caller knows that this can be awaited. It does not do anything special, but it helps clarify your code. You can use whatever suffix you think is right. I'm just used to the Async suffix.

修改

异步逻辑的Stackblitz示例

这篇关于为什么等待诺言不等待诺言解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆