为什么这个异步函数不隐含 return 一个承诺?

Why does this aysnc function not implicitly return a promise?

我在 Stack Overflow 问题 中读到:

"An Async function will always return a promise. If you don't explicitly return a promise, the value you return will automatically be wrapped in a promise."

那么为什么我的 getData2() 功能低于 return 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
})();

getData2 返回一个 Promise,但你正在 awaiting 它,它从 Promise 中提取解析值。

console.log(await getData2());

变成

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

如果您不 await 它,您将看到 Promise。

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

(async () => {
    console.log(getData2());
})();

解析值为 undefined 因为 getData2 的正文中没有返回任何内容。

问题不在于 async,而在于在内部函数(在本例中为 lambda)中使用 return,其中 return 来自该内部函数(not 外部函数),然后 setTimeout 忽略那个 return 值。正确的方法是 getData(但没有 async 关键字,它添加了第二层 Promise)。