2016-06-11 87 views
-1

为什么当承诺链有错误时,它不会执行.then,除非.then引用具有参数的外部方法?节点承诺链有错误但仍然执行。那么,为什么?

所以这个例子我故意在promise链中抛出一个错误。正如预期的那样,前三名不会开火。然而,最后一个有一个参数的方法会触发。为什么?正如预期的那样,接下来这个.catch会发生火灾。

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 

回答

1

这有什么好做的承诺。

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

那你是方法调用的返回值传递给then

1

.then(testMethod2(testVar))在这种方法中,你都没有通过testMethod2功能,那么,你是通过它的响应(因为在Javascript中你写funcName(funcParam)调用一个函数)

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

Function.prototype.bind

+0

谢谢!那工作 – sitbackmedia

+0

那么也许你应该接受答案?! – ali404