我正在关注 apollo 教程 ( https://www.apollographql.com/docs/tutorial/resolvers/ ),我看到了这段代码:
me: async (_, __, { dataSources }) =>
dataSources.userAPI.findOrCreateUser()
因为 dataSources.userAPI.findOrCreateUser()
返回 Promise,我想
await dataSources.userAPI.findOrCreateUser()
是正确的。
但它工作得非常好,没有任何错误,我在 React 中得到了解决的值(value)......即使下面的代码也工作得很好。
me: (_, __, { dataSources }) =>
dataSources.userAPI.findOrCreateUser()
这段代码让我很困惑。它是如何工作的?
最佳答案
除了启用 await
, async
implicitly wraps函数的结果变成了 Promise.resolve()
.大致:
async function() {
return something;
}
相当于:
function() {
return Promise.resolve(something);
}
事情是Promise.resolve()
“扁平化”它的参数,这意味着如果它的参数是一个thenable(例如另一个 Promise),它会自动“解决”它。换句话说,Promise.resolve(somethingThatIsAPromise).then(<work>)
与somethingThatIsAPromise.then(<work>)
效果相同.
MDN tries to explain that behavior (粗体是我的):
The
Promise.resolve()
method returns aPromise
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.
并且,由于箭头函数返回的 ( dataSources.userAPI.findOrCreateUser()
) 是一个 Promise,由于“扁平化”,具有 async
或不会以相同的行为结束。
关于javascript - 是否可以在没有异步/等待的情况下从 promise 返回已解析的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617248/