When I am chaining multiple promises and I expect that each promise will execute only after the previous one ended. Somehow it does not happen. I am sure using promises wrong and would love for some explanation.
I have this code:
var Promise = require('bluebird');
func('A')
.then(() => {func('B')})
.then(() => {func('C')})
.then(() => {func('D')})
function func(arg) {
return new Promise(function(resolve){
console.log('>> ' + arg);
setTimeout(function(){
console.log(' << ' + arg);
resolve();
}, 200)
})
}
I was expecting to get this output:
>> A
<< A
>> B
<< B
>> C
<< C
>> D
<< D
But instead, I get this output:
>> A
<< A
>> B
>> C
>> D
<< B
<< C
<< D
What am I getting wrong?
You need to return the promise
func('A')
.then(() => {return func('B')})
.then(() => {return func('C')})
.then(() => {return func('D')})
or
func('A')
.then(() => func('B'))
.then(() => func('C'))
.then(() => func('D'))
Ignoring Lexical this
or Lexical arguments
part,
() => {1}
translate to
function() { 1 } // return undefined
and () => 1
translate to
function() { return 1 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With