You resolve the promise returned from
setVal
before any of the
setTimeout
calls have executed.
You need to wait until all of the
setTimeout
calls have completed before resolving the promise. You'll want to create a separate promise for each call, and use
Promise.all[
^] to wait for them all to complete.
var delay = function(time, value){
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, value), time);
});
};
Promise.prototype.delay = function(time) {
return this.then(function(value) {
return delay(time, value);
});
};
var setVal = function(){
var promises = [];
for (var i = 0; i < 5; i++){
promises.push(Promise.resolve(i).delay(i * 1000).then(function(i){
console.log("Inside first", i);
}));
}
return Promise.all(promises);
};
var setVal1 = function(){
var promises = [];
for (var i = 0; i < 5; i++){
promises.push(Promise.resolve(i).delay(i * 1000).then(function(i){
console.log("Inside second", i);
}));
}
return Promise.all(promises);
};
setVal().then(setVal1);
javascript - using setTimeout on promise chain - Stack Overflow[
^]
Promise - JavaScript | MDN[
^]