GUIPSS

😎 Cool code : javascript promise unwrapping

Posted on: 2020-04-02
Categories:

As we have seen before, async and await are pretty easy to use once you understand that they are just another (great) way to play with promises.

One source of confusion that can arise when you learn about async/await is one mechanism of the Promise API that "unwrap" wrapped promises. To make it clear, check that code :

// an async function that return 1
const asyncFunc1 = async function () {
  return 1;
}

// an async function that returns a promise resolved with 1
const asyncFunc2 = async function () {
  return Promise.resolve(1);
}

// an async function that returns the result of a promise that resolve with 1
const asyncFunc3 = async function () {
  return await Promise.resolve(1);
}

// a regular function that return a promise resolved with 1
const returnAPromise1 = function () { // pas async
  return Promise.resolve(1);
}

// a regular function that return a promise resolved with another promise resolved with 1
const returnAPromise2 = function () { // pas async
  return Promise.resolve(Promise.resolve(1));
}

const main = () => {
  asyncFunc1().then(console.log);
  asyncFunc2().then(console.log);
  asyncFunc3().then(console.log);
  returnAPromise1().then(console.log);
  returnAPromise2().then(console.log);
}

main();

Now what's the result of this ?

1
1
1
1
1

If you're a beginner in the Promises/async/await world, the result might be a little confusing, but this functionality is actualy great, and normal when you think about it.

Keep in mind that the above functions did all returned different results, but when you use await or then, you can rest assured that you'll get what's important : the result of a deferred job (even if this job was deferred multiple times !)