i'm experimenting with es6 promises and chaining them and don't understand why my example doesn't work.
i want to chain printInterval() and setInterval() multiple times and expect _interval to decrease like this:
- waited 3000ms to display this message
- setting interval to 2000
- waited 2000ms to display this message
- setting interval to 1000
- waited 1000ms to display this message
- setting interval to 500
- waited 500ms to display this message
but i get the following:
- waited 3000ms to display this message
- setting interval to 2000
- setting interval to 1000
- setting interval to 500
- waited 500ms to display this message
- waited 500ms to display this message
- waited 500ms to display this message
.
function printInterval() {
return new Promise(function(resolve, reject){
setTimeout(function () {
console.log('waited ' + _interval + 'ms to display this message')
resolve(_interval);
}, _interval)
})
}
function setInterval(interval){
return new Promise(function(resolve, reject) {
setTimeout(function () {
console.log('setting interval to ', interval)
_interval = interval;
resolve(_interval);
}, 0);
})
}
var _interval = 3000;
printInterval()
.then(function(){setInterval(2000)})
.then(function(){printInterval()})
.then(function(){setInterval(1000)})
.then(function(){printInterval()})
.then(function(){setInterval(500)})
.then(function(){printInterval()});
thank you!
You should
return
those functions not just call them: