【问题标题】:Typescript async / await Promise call difference?Typescript async / await Promise 调用区别?
【发布时间】:2016-02-26 18:38:04
【问题描述】:

如果在 Typescript 1.7 / ES7 我有三个功能:

async function f(): Promise<int> { /* ... */ }

async function g(): Promise<int> {
    return f();
}

async function h(): Promise<int> {
    return await f();
}

这些调用之间有什么区别:

g();    
h();    
await g();    
await h();    

【问题讨论】:

    标签: javascript asynchronous ecmascript-2016 typescript1.7


    【解决方案1】:

    g();这样直接调用异步函数会返回一个可以解析/拒绝的Promise

    g().then((result) => {
      doSomethingWith(result);
      doSomethingElseWith(result);
    });
    

    在另一个Promise 中返回一个Promise(这是return f(); 所做的)将用内部promise 的值解析外部promise。

    只需调用g() 将启动g 正在执行的任何操作,而不是等待其完成,丢弃结果。

    await 调用g 要求封闭范围也是async 函数,概念上“等待”g“返回”(解决/拒绝,实际上)。


    使用await 关键字调用异步函数与不使用await 并使用Promise 调用基本相同,只是语法更好。所以这个:

    async function f () { ... }
    
    try {
      var result = await f();
      doSomethingWith(result);
    } catch (error) {
      handle(error);
    }
    

    其实和这个是一样的:

    async function f() { ... }
    
    f().then(
      (result) => doSomethingWith(result),
      (error) => handle(error)
    );
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 2019-09-25
      • 2023-03-10
      • 1970-01-01
      • 2019-04-30
      • 2022-08-22
      • 2017-05-29
      • 1970-01-01
      相关资源
      最近更新 更多