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.