当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - promise chaining when splitting the chain

问题描述:

In the following code

var p = new Promise((resolve, reject) => {

console.log('a');

resolve();

});

p.then(() => {

console.log('b');

}).then(() => {

console.log('c');

});

p.then(() => {

console.log('z');

})

I expect the console output to be:

a

b

c

z

Instead I got:

a

b

z

c

but with this code I got the expected result

var p = new Promise((resolve, reject) => {

console.log('a');

resolve();

}).then(() => {

console.log('b');

}).then(() => {

console.log('c');

});

p.then(() => {

console.log('z');

})

Can anyone explain the way promise chaining is done in this case?

网友答案:

Each then returns you new Promise which depends of callback resolution.

That's difference.

var p = new Promise((resolve, reject) => {
    console.log('a');
    resolve();
});

var a = p.then(() => {    
    console.log('b');

});
a.then(() => {    
    console.log('c');    
});

p.then(() => {
    console.log('z');
});

Timeline:

  • initial resolve // a
  • p resolved // b, z independently
  • a resolved // c

In second case your p points to promise returned by last then:

var a = new Promise(foo('a'));
var b = a.then(foo('b'));
var p = b.then(foo('c'));
p.then(foo('z'));

You should not to rely on one level resolving order. Because this happens eventually and order is realy undefined(depend on internal implementation).

分享给朋友:
您可能感兴趣的文章:
随机阅读: