I am currently waiting for all the promise to finish sequentially like this:
(async() => {
let profile = await profileHelper.getUserData(username);
let token = await tokenHelper.getUserToken(username);
console.log(profile);
console.log(token);
return {profile: profile, token: token};
})();
But this way, profile and token executes sequentially. Since both are independent of each other, I want both of them to be executed independently together. I think this can be done using Promise.all, but I am not sure of the syntax and I could not find any help as well.
So my question is how I can convert above api calls to run together and then return the final output.
If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result. Here is an example with a promise that resolves in 2 seconds.
all() with async-await. Example 1: In this example we will creating two promises inside two different functions (or methods) and in another function we will accessing them using Promise. all() along with making that function as async and promise resulting fetching will be done along with the await keyword.
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
(async() => {
const [ profile, token ] = await Promise.all([
profileHelper.getUserData(username),
tokenHelper.getUserToken(username)
]);
return { profile, token };
})();
use Promise.all()
method:
(async() => {
let [ profile, token ] = await Promise.all(
[profileHelper.getUserData(username),
tokenHelper.getUserToken(username)
])
return {profile: profile, token: token};
})();
Wait until all ES6 promises complete, even rejected promises
You want to use Promise.all
The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.
(async() => {
const response = await Promise.all([
profileHelper.getUserData(username),
tokenHelper.getUserToken(username)
]);
return {profile: response[0], token: response[1]};
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With