【问题标题】:Is it possible to return resolved value from promise without async/await?是否可以在没有 async/await 的情况下从 Promise 返回已解析的值?
【发布时间】:2019-10-30 05:12:53
【问题描述】:

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

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

因为dataSources.userAPI.findOrCreateUser()返回Promise,我想 await dataSources.userAPI.findOrCreateUser() 是对的。

但它运行得非常好,没有任何错误,我在 React 中得到了解析值......即使下面的代码也运行良好。

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

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

【问题讨论】:

  • 您只需要async,如果您要: 1. await 某事;或者 2. 返回一个非承诺值,您希望将其包含在承诺中。如果你已经返回了一个promise,不管函数是不是async,结果都是一样的。
  • @jonrsharpe 哦……我明白了……谢谢你告诉我

标签: javascript node.js asynchronous async-await apollo


【解决方案1】:

除了启用await,asyncimplicitly 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(粗体是我的):

Promise.resolve() 方法返回一个被解析的Promise 对象 具有给定值。 如果该值是一个承诺,则该承诺是 返回;如果该值是 thenable(即具有 "then" method),则 返回的承诺将“跟随”那个thenable,采用它的最终 状态;否则返回的承诺将与 价值。这个函数flatten嵌套层的promise-like对象 (例如,一个解决为解决某事的承诺的承诺) 单层。

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

【讨论】:

  • 非常感谢。直到现在我才知道...感谢您让我知道这些有用的信息!
猜你喜欢
  • 2017-05-21
  • 2017-09-11
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 2017-09-08
  • 2020-02-06
相关资源
最近更新 更多