-1

Why when a promise chain has an error it will not execute .then unless the .then references an external method with a parameter?

So this example I purposely throw an error in the promise chain. The first three .then's do not fire, as expected. However, the last .then that has a method with a parameter, fires. Why? And then the .catch fires, as expected.

    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??');
    }

Results in the console:

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

2 Answers2

2

.then(testMethod2(testVar)) In this method you are not passing the testMethod2 function to then, you are passing its response (Because in Javascript you call a function by writing funcName(funcParam))

to pass the function with some parameters you have to call it like this: .then(testMethod2.bind(this, testVar))

Function.prototype.bind

ali404
  • 1,143
  • 7
  • 13
1

This has nothing to do with promises.

You are invoking the method immediately: testMethod2(testVar)

Then you are passing the return value of that method invocation to then.

user229044
  • 232,980
  • 40
  • 330
  • 338