DEV Community

Discussion on: Understanding JavaScript async/await in 7 seconds

 
wassimchegham profile image
Wassim Chegham • Edited

Hey, so for your particular use case, I would try this:

const profilePromise = getProfile(this.id);
const commentsPromise = getComments(this.id)
const friendsPromise = getFriends(this.id);

this.profile = await profilePromise;
this.comments = await commentsPromise;
this.friends = await friendsPromise;

Here is a working proof of concept:

const func = (t, f) => new Promise( (res, rej) => { setTimeout( () => res(f()), t )  } )
const a = func(2000, () => console.log('func 1'));
const b = func(0, () => console.log('func 2'));
const c = func(0, () => console.log('func 3'));
const [f1, f2, f3] = [await a, await b, await c];

console.log(f1, f2, f3);

Thread Thread
 
madslundt profile image
Mads

To run them parallel there is this approach:

const result = await Promise.all([
  getProfile(this.id), 
  getComments(this.id),
  getFriends(this.id),
]);

However, this waits for all to finish and does not replace the first I descried, as I see it?

As I see it the only way to avoid this with async/await is to wrap the promises into their own function and run it in Promise.all. Like this (haven't tested this yet):

await Promise.all([
  async () => { this.profile = await getProfile(id); },
  async () => { this.comments = await getComments(id); },
  async () => { this.friends = await getFriends(id); },
]);
Thread Thread
 
prasannasridharan profile image
Prasanna-Sridharan

Hi,
As I see it, in both cases the inner methods run async and the end promise is awaited so it would not be blocking the current thread anyway.
When I get time, will execute 2nd e.g. but highly doubt if it has any difference in behavior compared to 1st.