w3resource

Resolving Nested Promises in JavaScript with Async/Await


Handling Nested Promises:

Write a JavaScript function that resolves a nested Promise structure using async/await.

Solution-1:

Code:

// Function that returns a nested Promise structure
function getNestedPromise() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(
        new Promise((resolve) => {
          setTimeout(() => resolve('Nested Promise Resolved!'), 1000);
        })
      );
    }, 1000);
  });
}

// Async function to resolve the nested Promise structure
async function handleNestedPromise() {
  const firstLevel = await getNestedPromise(); // Resolves the outer promise
  const result = await firstLevel; // Resolves the nested promise
  console.log(result); // Output: Nested Promise Resolved!
}

handleNestedPromise();


Output:

"Nested Promise Resolved!"

Explanation:

  • 'getNestedPromise' returns a Promise that resolves to another Promise after 1 second.
  • The async function 'handleNestedPromise' uses 'await' to resolve the outer promise first.
  • It then resolves the nested promise and logs the result.

Solution-2:

Code:

function getMultiNestedPromise() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(
        new Promise((resolve) => {
          setTimeout(() => {
            resolve(
              new Promise((resolve) => {
                setTimeout(() => resolve('Deeply Nested Promise Resolved!'), 500);
              })
            );
          }, 1000);
        })
      );
    }, 1000);
  });
}

// Async function to handle multi-level nested Promises
async function handleMultiNestedPromise() {
  const firstLevel = await getMultiNestedPromise(); // Resolves the outermost promise
  const secondLevel = await firstLevel; // Resolves the second level promise
  const result = await secondLevel; // Resolves the innermost promise
  console.log(result); // Output: Deeply Nested Promise Resolved!
}

handleMultiNestedPromise();

Output:

"Deeply Nested Promise Resolved!"

Explanation:

  • 'getMultiNestedPromise' creates a multi-level nested Promise structure.
  • The async function 'handleMultiNestedPromise' resolves each level in sequence using 'await'.
  • The final resolved value of the innermost promise is logged.

See the Pen promises-and-async-await-exercise-16 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Promise.race in JavaScript with Practical Examples.
Next: Simulate a Loading Spinner for Async Operations in JavaScript.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.