DEV Community

Discussion on: I Promise this is a practical guide to Async / Await

Collapse
 
namirsab profile image
Namir

Hey Micha!
Nice post!

There is a better way to chain promises one after another. You can just return a promise within a then callback, like this:

resolveAfterXSeconds(2000)
  .then((ms) => { 
    console.log('promise in the first then');
    console.log(`resolved after ${ms}`);

    return resolveAfterXSeconds(1000);
  }).then((ms) => { console.log(`resolved after ${ms}`) });

Enter fullscreen mode Exit fullscreen mode

This way you can avoid the similarity of the "callback" hell, and you get exactly the same result in a more readable way.
First of all execute the code after 2 seconds, and then execute the code after 1 seconds.

PS: Btw, the name of the function should be resolveAfterXMilliseconds

Collapse
 
vbarzana profile image
Victor A. Barzana

Lol wanted to say the same 😉 great article btw

Collapse
 
lampewebdev profile image
Michael "lampe" Lazarski • Edited

Hey Namir,
Thanks.

yes, this is another solution is to chain the promises. Like I have written that the given first example is just an example I have seen and should be more an anti-pattern. If you chain a lot of promises, so what you want to run your code in a sequential manner then I think that Await / Async is the even more readable solution.

time = await resolveAfterXSeconds(2000);
console.log(`resolved after ${time}`);
time = await resolveAfterXSeconds(1000);
console.log(`resolved after ${time}`);