Categories
JavaScript Answers

How to return a variable from the child promise with JavaScript?

Spread the love

Sometimes, we want to return a variable from the child promise with JavaScript.

In this article, we’ll look at how to return a variable from the child promise with JavaScript.

How to return a variable from the child promise with JavaScript?

To return a variable from the child promise with JavaScript, we use async and await.

For instance, we write

const top = async () => {
  const parent = await ParentPromise();
  const child = await ChildPromise(parent.id);
  return child.result.items;
};

to define the top function.

In it, we get the result of the ParentPromise promise with await.

And then we get the result of the ChildPromise promise with await.

Finally, we return the child.result.items property.

We can then use

const items = await top();

to get the value in another async function.

Conclusion

To return a variable from the child promise with JavaScript, we use async and await.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *