节点承诺链有错误,但仍然执行.那么,为什么



为什么当承诺链出现错误时,它不会执行.then,除非.then引用带有参数的外部方法?

所以在这个例子中,我故意在promise链中抛出一个错误。前三个。然后我们不要像预期的那样开火。然而,具有带参数的方法的最后一个.then会激发。为什么?然后,不出所料,他们着火了。

var Promise = require('bluebird');
var testVar = 'foo';
errorOnPurpose()
.then(function() {
console.log('This will not fire, as expected');
})
.then(function(testVar) {
console.log('This also will not fire, as expected');
})
.then(testMethod1)
.then(testMethod2(testVar))
.catch(function(error) {
console.log('Error:::', error, ' , as expected');
});
function errorOnPurpose() {
return new Promise(function(resolve, reject) {
return reject('This promise returns a rejection');
});
}
function testMethod1() {
console.log('This one will not fire either, as expected');
}
function testMethod2(foo) {
console.log('This will fire!!!!, ARE YOU KIDDING ME!! WHY??');
}

控制台中的结果:

This will fire!!!!, ARE YOU KIDDING ME!! WHY??
Error::: This promise returns a rejection  , as expected

.then(testMethod2(testVar))在这个方法中,您没有将testMethod2函数传递给它,而是传递它的响应(因为在Javascript中,您通过编写funcName(funcParam)来调用函数)

要传递带有一些参数的函数,您必须这样调用它:.then(testMethod2.bind(this, testVar))

功能.模式.绑定

这与承诺无关。

您正在立即调用方法:testMethod2(testVar)

然后将该方法调用的返回值传递给then

相关内容

最新更新