简体   繁体   中英

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:

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

Because dataSources.userAPI.findOrCreateUser() returns Promise , I thought that await dataSources.userAPI.findOrCreateUser() was right.

But it working really well without any errors and I got resolved value in React... even this below code working well too.

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() . 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. In other words, Promise.resolve(somethingThatIsAPromise).then(<work>) has the same effect of somethingThatIsAPromise.then(<work>) .

MDN tries to explain that behavior (bold is mine):

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 (ie 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 (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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