Sometimes, we want to return result from a promise then() with JavaScript.
In this article, we’ll look at how to return result from a promise then() with JavaScript.
How to return result from a promise then() with JavaScript?
To return result from a promise then() with JavaScript, we can return a value in an async function.
Then we can use await to get the returned value.
For instance, we write
const request = async (output) => {
const response = await axios.get(getApiHost() + "/api/some_endpoint");
return response;
};
const test = async () => {
const result = await request(output);
return result + 1;
};
to define the request function that returns the response from the promise returned by axios.get.
And then in test, we use await with request to get the resolve value of the promise returned by request, which is the response.
And then we add 1 to result and return the sum.
Conclusion
To return result from a promise then() with JavaScript, we can return a value in an async function.
Then we can use await to get the returned value.