Sometimes, we want to wait for a promise to finish before returning the variable of a function with JavaScript.
In this article, we’ll look at how to wait for a promise to finish before returning the variable of a function with JavaScript.
How to wait for a promise to finish before returning the variable of a function with JavaScript?
To wait for a promise to finish before returning the variable of a function with JavaScript, we can use await
.
For instance, we write
const waitForPromise = async () => {
let result = await Promise.resolve("hello");
};
to create the waitForPromise
function that calls Promise.resolve
to return a promise.
Then we use await
to wait for the result of the promise and get the result before we continue running the function.
Conclusion
To wait for a promise to finish before returning the variable of a function with JavaScript, we can use await
.