我给人的印象是,一个承诺链返回了“ then”链中的最后一个承诺。但是,当我测试以下内容时,情况似乎并非如此:
function a() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('1');
resolve(1);
}, 1000);
}).then((num) => {
setTimeout(function() {
console.log('2');
return 2;
}, 1000);
});
}
a().then((num) => {
console.log('a is done running');
console.log('finally, ', num);
});
该代码当前输出
1
a is done running
finally, undefined
2
最底层的履行功能不应该仅在链中的所有承诺都完成后才运行吗?
我将如何输出以下内容?
1
2
a is done running
finally, 2
最佳答案
您可以通过实际返回新的承诺来做到这一点:
function a() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('1');
resolve(1);
}, 1000);
}).then((num) => {
return new Promise((resolve) => {
setTimeout(function() {
console.log('2');
return resolve(2);
}, 1000);
})
});
}
// the "then" here actually comes from the second promise.
a().then((num) => {
console.log('a is done running');
console.log('finally, ', num);
});