我想链3承诺在一起,但有一些行为,我不知道有关resolve
和reject
功能。我已经简化我的代码,以便提出这样的问题:本地JavaScript链接承诺
function testP(num) {
return new Promise((resolve, reject) => {
console.log('Do Work', num);
reject(num);
});
}
function testPromises() {
return new Promise((resolve, reject) => {
testP(1)
.then(testP(2))
.then(testP(3))
.then(resolve)
.catch(reject);
});
};
const theTest = testPromises().then(()=>{
console.log("all done");
}).catch(err => {
console.log("ERR", err);
});
而我所看到的在我的输出是:
Do Work 1
Do Work 2
Do Work 3
ERR 1
为什么代码得到Do Work 2
和Do Work 3
,如果第一诺言立即命中reject
?我的理解是then
函数在执行前等待resolve
或reject
的承诺。
顺便说一句'返回新无极((解析,拒绝)=> {不便( )。然后(smth2)。然后(解析).catch(拒绝); })'是反模式。使用'return smth()。then(smth2);'更好。 –