我想将3个诺言链接在一起,但是关于resolve
和reject
功能,有些行为我无法弄清楚。我简化了我的代码,以问这个问题:
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
执行前。
因为当你做
.then(testP(2))
您立即无条件调用 testP
,传入2,然后将其返回值传递到中.then
,方法与foo(bar())
调用 bar
并将其返回值传递到中的方式完全相同foo
。
这段代码:
testP(1)
.then(testP(2))
.then(testP(3))
.then(resolve)
.catch(reject);
的评估方式如下(省略了一些次要细节):
testP
值1并将结果值记为p1
testP
以值2呼叫p1.then
用该调用的结果进行调用,并将结果值记为P2testP
值3p2.then
用该调用的结果进行调用,并将结果值记为p3
p3.then
该值resolve
并将结果记为p4
p4.catch
用值调用reject
reject
第一次调用函数testP
与值1reject
fromtestPromises
如果您希望testP
等到第一个解决之后,就不调用它,而是传递对它的引用:
.then(testP)
如果希望加入参数,请使用bind
:
.then(testP.bind(null, 2))
或内联函数:
.then(function() {
return testP(2);
})
示例(需要使用的浏览器Promise
):
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.bind(null, 2))
.then(testP.bind(null, 3))
.then(resolve)
.catch(reject);
});
};
const theTest = testPromises().then(()=>{
console.log("all done");
}).catch(err => {
console.log("ERR", err);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句