0

For prevent hell pyramid programming, I'm looking for use "Promise" with I'm still not familar.

By example, I have this ugly code :

var timeA = 500;
var timeB = 800;
var timeC = 750;

window.setTimeout(function(){
    //do stuff 1
    window.setTimeout(function(){
    //do stuff 2
        window.setTimeout(function(){
        //do stuff 3
        }, timeA);
    }, timeB);
}, timeC);

How must I change my code by using Promise mechanism ? Thank you :)

Mikev
  • 2,012
  • 1
  • 15
  • 27
spacecodeur
  • 2,206
  • 7
  • 35
  • 71

3 Answers3

2

You will need to wrap setTimeout into a Promise.

Below I've also shown how you can then use with async / await..

var timeA = 500;
var timeB = 800;
var timeC = 750;

function wait(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

/*wait(timeA).
  then(() => console.log("timeA")).
  then(() => wait(timeB)).
  then(() => console.log("timeB")).
  then(() => wait(timeC)).
  then(() => console.log("timeC")); */

async function run() {
  await wait(timeA);
  console.log("timeA")
  await wait(timeB);
  console.log("timeB")
  await wait(timeC);
  console.log("timeC");
}

run();
Keith
  • 22,005
  • 2
  • 27
  • 44
1

You could create a "promisifying" function this way:

function doLater(thunk, delay){
    return new Promise(function(resolve, reject){
        window.setTimeout(function() {
            resolve(thunk());
        }, delay);
    });
}

Then you can call it this way:

doLater(doSomething, delay1)
    .then(result => doLater(doSomethingElse, delay2)
    .then(result => doLater(doAnotherThing(result), delay3)
Kraylog
  • 7,383
  • 1
  • 24
  • 35
1

For example:

var timeA = 500;
var timeB = 800;
var timeC = 750;
var wait = (seconds) => new Promise(r => setTimeout(r, seconds));

wait(timeA)
  .then(() => console.log('A'))
  .then(() => wait(timeB))
  .then(() => console.log('B'))
  .then(() => wait(timeC))
  .then(() => console.log('C'));

But when you are dealing with asynchronicity, using setTimeout is almost always not what you would use.

str
  • 42,689
  • 17
  • 109
  • 127