javascript - 是否可以在没有异步/等待的情况下从 promise 返回已解析的值?

标签 javascript node.js asynchronous async-await apollo

我正在关注 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 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.

并且,由于箭头函数返回的 ( dataSources.userAPI.findOrCreateUser() ) 是一个 Promise,由于“扁平化”,具有 async或不会以相同的行为结束。

关于javascript - 是否可以在没有异步/等待的情况下从 promise 返回已解析的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617248/

相关文章:

javascript - 在 promise resolve 方法中状态总是过时的

node.js - 网站流量和内存使用量之间有什么关系?

ajax - Firefox 似乎正在对并行 ajax 请求的成功函数进行排队,可能是因为 setTimeout?

具有并发性的 Python 线程

javascript - 在 worklight 中从服务器返回结果集数组

javascript - 为什么我的顶级菜单项之一仅在 ie10 中未对齐?

javascript - AudioBufferSourceNode.stop() 是否需要 'this' 绑定(bind)?

javascript - back4app 云代码无效功能问题

node.js - 如何查询MongoDb中的所有项目

c++ - gRPC cpp 异步服务器与同步服务器