【问题标题】:details of async/await in typescript打字稿中异步/等待的详细信息
【发布时间】:2016-10-01 17:19:50
【问题描述】:

我已经阅读了有关该主题的各种介绍文本,但我仍然对细节感到困惑(在 nodejs 中)。

async function a() {
    const e = await Promise.resolve(42);
    console.log(e);
    return e;
}
const b = a();
console.log(b);

展示

Promise { <pending> }
42

b 和 e 不一样的解释是什么?删除等待后我得到了

Promise { 42 }
Promise { <pending> }

又不一样了。用普通数字 42 替换 e 初始化的右侧给了我对 b 的另一个承诺

42
Promise { 42 }

你能解释一下吗?

【问题讨论】:

    标签: node.js asynchronous typescript


    【解决方案1】:

    因为它的异步

    您认为eb 之前打印。但事实并非如此。 b 指向调用a 的最终承诺(因此b Promise)。而a 执行e 仅来自yield 结果(e = await somPromise)。所以e 指向解析的值。

    以下内容很有帮助:

    async function a() {
        const e = await Promise.resolve(42);
        console.log('e',e);
        return e;
    }
    const b = a();
    console.log('b',b);
    

    打印出来的

    b Promise { <pending> }
    e 42
    

    更多

    一些文档https://basarat.gitbooks.io/typescript/content/docs/async-await.html

    【讨论】:

      【解决方案2】:

      async 函数在找到 await 时会暂停,而它之外的代码会继续执行。

      简而言之,当console.log(b) 被执行时,异步函数还没有解析,所以你得到&lt;pending&gt; 状态。在下一个tick 中,promise 解决了,async 函数继续你在那里得到 42。

      在你的最后一部分中,await 没有暂停函数,因为没有承诺,所以你马上得到 42。

      【讨论】:

        【解决方案3】:

        一个实用的方法是在async函数中,在await之后,你在then中,即

        async function a(): Promise<number> {
            const e = await Promise.resolve(42);
            //now "in a then"
            console.log('e',e);
            return e;
        }
        

        有点(await 等待)相当于

        function a(): Promise<number> {
            return Promise.resolve(42)
              //now "in a then"
              .then(e => {
                console.log('e',e);
                return e;
              })
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-03
          • 2019-03-18
          • 2018-03-08
          • 2016-10-20
          • 1970-01-01
          • 2023-02-21
          相关资源
          最近更新 更多