2016-06-11 1 views
-1

プロミスチェーンにエラーが発生したときに、.thenがパラメータを持つ外部メソッドを参照しない限り、実行しません。ノード・プロミス・チェーンにはエラーがありますが、依然として.then、なぜですか?

この例では、私は意図的に約束のチェーンにエラーを投げます。最初の3つは、期待通りに発射されません。しかし、最後にパラメータを持つメソッドを持っていると、それが発生します。どうして?そして、.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にそのメソッド呼び出しの戻り値を渡しています。あなたが呼び出す必要がありますいくつかのパラメータを持つ関数を渡すために(JavaScriptであなたがfuncName(funcParam)を書くことで関数を呼び出すので)あなたがその応答を渡している、その後に

をtestMethod2機能を渡していません。この方法では

1

.then(testMethod2(testVar))それこのような: .then(testMethod2.bind(this, testVar))

Function.prototype.bind

+0

ありがとうございます!それは – sitbackmedia

+0

を働かせました。多分あなたは答えを受け入れるべきですか? – ali404

関連する問題