Nina S Nina S - 6 months ago 9
Javascript Question

Promise chain order

I use the following code and there is something that a bit confuse me
if I put in the timeout 1000ms I see that the promise called in the right order
but if I change it to the following

This is step 3
This is step 2
This is step 1


I guess that this happen since when the function is
resolved
then he proceed to the
next function
am I correct ? if this is true how can I do this chain that when the first is finished
then
he proceed to the second etc but without using the promise hell :-)

https://jsfiddle.net/2yym400j/

var step1 = function(ms) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("This is step 1");
resolve();
}, ms);
})
}
var step2 = function(ms) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("This is step 2");
resolve();
}, ms);
})
};
var step3 = function(ms) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("This is step 3");
resolve();
}, ms);
})
};


step1(500)
.then(step2(300))
.then(step3(200))
.catch(function(err) {
console.log(err);
});

Answer

Just pass a function instead of the result of the steps.

step1(500)
   .then(function() { return step2(300); })
   .then(function() { return step3(200); })
   .catch(function(err) {
      console.log(err);
   });

Without this, you are just calling each step without "blocking" for the previous step to resolve.