没有 async/await 是否可以 return 从 promise 中解析值?

Is it possible to return resolved value from promise without async/await?

我正在关注 apollo 教程 (https://www.apollographql.com/docs/tutorial/resolvers/),我看到了这段代码:

me: async (_, __, { dataSources }) =>
  dataSources.userAPI.findOrCreateUser()

因为dataSources.userAPI.findOrCreateUser()returnsPromise,我以为 await dataSources.userAPI.findOrCreateUser() 是对的。

但它工作得很好,没有任何错误,我在 React 中得到了解决的价值……即使下面的代码也工作得很好。

me: (_, __, { dataSources }) =>
  dataSources.userAPI.findOrCreateUser()

这段代码让我很困惑。它是如何工作的?

除了启用await外,asyncimplicitly wraps函数的结果变成了Promise.resolve()。大致:

async function() {
  return something;
}

相当于:

function() {
  return Promise.resolve(something);
}

事情是 Promise.resolve() "flattens" 它的参数,这意味着如果它的参数是 thenable (例如另一个 Promise)它会自动 "resolves" 给它。换句话说,Promise.resolve(somethingThatIsAPromise).then(<work>)somethingThatIsAPromise.then(<work>) 具有相同的效果。

MDN tries to explain that behavior(粗体是我的):

The Promise.resolve() method returns a Promise object that is resolved with a given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer.

而且,由于你的箭头函数 returns (dataSources.userAPI.findOrCreateUser()) 是一个 Promise,由于 "flattening",有或没有 async 最终都相同行为。