Wait until everyone promises to complete nodejs (asynchronous wait)

Currently, I expect all promises to end as follows:

(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 in this way, the profile and token are executed sequentially. Since both of them are independent of each other, I want both of them to be executed independently of each other. I think this can be done using Promise.all, but I am not sure of the syntax, and I also did not find any help.

So my question is how can I convert over api calls to work together and then return the final output.

+4
source share
3 answers
(async() => {
  const [ profile, token ] = await Promise.all([
    profileHelper.getUserData(username),
    tokenHelper.getUserToken(username)
  ]);

  return { profile, token };
})();
+5
source

use Promise.all()method:

(async() => {
 let [ profile, token ] = await Promise.all(
  [profileHelper.getUserData(username), 
  tokenHelper.getUserToken(username)
 ])
 return {profile: profile, token: token};
})();

ES6 promises, promises

+4

Promise.all

The Promise.all (iterable) method returns one promise that resolves when all promises in the iterative argument are resolved or when the iterative argument does not contain promises. He rejects the reason for the first promise, which he rejects.

(async() => {
  const response = await Promise.all([
    profileHelper.getUserData(username),
    tokenHelper.getUserToken(username)
  ]);

  return {profile: response[0], token: response[1]};
})();
+2
source

Source: https://habr.com/ru/post/1693315/


All Articles