代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

为什么此aysnc函数不隐式返回承诺?

  •  1
  • Edward Tanguay  · 技术社区  · 4 年前

    我读了这个堆栈溢出问题 async/await implicitly returns promise? 即:

    “异步函数将始终返回一个承诺。如果你不 以承诺为包装。”

    那么为什么我的 getData2() 函数低于返回 undefined

    const getData = async() => {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('this is the data');
        }, 2000);
      });
    };
    
    const getData2 = async() => {
      setTimeout(() => {
        return 'this is the data without an explicit promise';
      }, 1000);
    };
    
    (async() => {
      console.log(await getData2()); // DOES NOT WORK: displays 'undefined' immediately
      console.log(await getData()); // WORKS: waits one second and displays data
    })();
    2 回复  |  直到 4 年前
        1
  •  3
  •   CertainPerformance    4 年前

    getData2 回报一个承诺,但你 await

    console.log(await getData2());
    

    变成

    console.log(await promiseThatResolvesToUndefined);
    
    console.log(undefined);
    

    如果你不 等待 它,你会看到承诺。

    const getData2 = async () => {
        setTimeout(() => {
            return 'this is the data without an explicit promise';
        }, 1000);
    };
    
    (async () => {
        console.log(getData2());
    })();

    解析值为 undefined .

        2
  •  1
  •   Solomon Ucko    4 年前

    async 但是在内部函数(在本例中是lambda)中使用return,该函数从该内部函数返回( 外部功能),以及 setTimeout 然后忽略该返回值。正确的方法是 getData (但没有 异步的 关键字,它添加了第二层 Promise ).