Im a little lost and I think Im hitting "cant see the wood for the trees syndrome".
Im a JS NooB and Im trying to understand how to call a set of JS functions (which return promises) in order. Ive done some reading up and have decided that given Im using Node I should use something like bluebird to manage the promises..
What I cant work out is why this piece of code doesnt work
var Promise = require("bluebird");
// My Promise enabled function from oReily Safari book
function countdown(seconds, timername) {
return new Promise(function (resolve, reject) {
console.log('Countdown : Starting Countdown ' + timername);
for (let i = seconds; i >= 0; i--) {
setTimeout(function () {
if (i > 0)
console.log(timername + ' ' + i + '...');
else
{
console.log('countdown '+timername+' now=='+i+' resolving!');
resolve(console.log("Countdown : timename="+timername+" ended"));
}
}, (seconds - i) * 1000);
}
});
}
/*Basic test of promise */
/* when this is run I expected countdown(5, 'Basic : Timer1') to execute and then when **resolved** THEN countdown(5, "Basic Timer2") to execute.
*however what I see is both timers executing at the same time..
*/
console.log('Basic : Countdown promise test');
countdown(5, 'Basic : Timer1').
then(function ()
{
/*Success */
console.log("Basic : Ended Successfully");
}).
then(countdown(5, "Basic : Timer2")
);
When I run this I am expecting countdown(5,'timer1') to execute first and then , only when timer1 has finished, will timer2 get executed..
However when I run this I get
Basic : Countdown promise test
Countdown : Starting Countdown Basic : Timer1
Countdown : Starting Countdown Basic : Timer2
Basic : Timer1 5...
Basic : Timer2 5...
Basic : Timer1 4...
Basic : Timer2 4...
Basic : Timer1 3...
Basic : Timer2 3...
Basic : Timer1 2...
Basic : Timer2 2...
Basic : Timer1 1...
Basic : Timer2 1...
countdown Basic : Timer1 now==0 resolving!
Countdown : timename=Basic : Timer1 ended
countdown Basic : Timer2 now==0 resolving!
Countdown : timename=Basic : Timer2 ended
Basic : Ended Successfully
Done.
Im lost..
Many thanks in advance
then(countdowshould bethen(x=> countdown())