简体   繁体   English

是否可以在没有 async/await 的情况下从 promise 返回已解析的值?

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

I am following apollo tutorials ( https://www.apollographql.com/docs/tutorial/resolvers/ ) and I saw this code:我正在关注阿波罗教程( https://www.apollographql.com/docs/tutorial/resolvers/ ),我看到了这段代码:

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

Because dataSources.userAPI.findOrCreateUser() returns Promise , I thought that await dataSources.userAPI.findOrCreateUser() was right.因为dataSources.userAPI.findOrCreateUser()返回Promise ,我认为await dataSources.userAPI.findOrCreateUser()是正确的。

But it working really well without any errors and I got resolved value in React... even this below code working well too.但它运行得非常好,没有任何错误,我在 React 中得到了解决的价值……即使是下面的代码也运行良好。

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

This code makes me confused.这段代码让我很困惑。 How does it work?它是如何工作的?

Besides enabling await , async implicitly wraps the result of the function into a Promise.resolve() .除了启用awaitasync 隐式地将函数的结果包装Promise.resolve() Roughly:大致:

async function() {
  return something;
}

Is equivalent to:相当于:

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

The thing is Promise.resolve() "flattens" its argument, meaning if its argument is a thenable (such as another Promise) it automatically "resolves" to it.事情是Promise.resolve() “扁平化”它的参数,这意味着如果它的参数是一个thenable (例如另一个 Promise),它会自动“解析”它。 In other words, Promise.resolve(somethingThatIsAPromise).then(<work>) has the same effect of somethingThatIsAPromise.then(<work>) .换句话说, Promise.resolve(somethingThatIsAPromise).then(<work>)具有与somethingThatIsAPromise.then(<work>)相同的效果。

MDN tries to explain that behavior (bold is mine): MDN 试图解释这种行为(粗体是我的):

The Promise.resolve() method returns a Promise object that is resolved with a given value. Promise.resolve()方法返回一个使用给定值解析的Promise对象。 If the value is a promise, that promise is returned ;如果值是一个承诺,则返回该承诺 if the value is a thenable (ie has a " then " method ), the returned promise will "follow" that thenable, adopting its eventual state;如果值是 thenable(即有一个then ”方法),则返回的 promise 将“跟随”那个 thenable,采用它的最终状态; otherwise the returned promise will be fulfilled with the value.否则返回的承诺将用该值实现。 This function flattens nested layers of promise-like objects (eg a promise that resolves to a promise that resolves to something) into a single layer.该函数将嵌套的类似承诺的对象层(例如,解析为解析为某事的承诺的承诺)扁平化为单个层。

And, since what your arrow functions returns ( dataSources.userAPI.findOrCreateUser() ) is a Promise, due to that "flattening", having async or not ends up in the same behavior.而且,由于您的箭头函数返回的内容( dataSources.userAPI.findOrCreateUser() )是一个 Promise,由于“扁平化”, async与否最终会以相同的行为结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM