Search code examples
javascriptnode.jspromisebluebird

bluebird Promise chain this reference


i am struggling with a class with several functions. Each of them returns a promise.

My problem is, that after the first return of a Promise, the this-reference in the next function is not the class object but the global node object.

Here is some sample code:

index.js:

"use strict";

const debug = require("./dbg.js");
const testClass = require("./testClass.js");


const dbg = new debug();

const tc = new testClass(dbg);


tc.printTestMessage()
    .then(tc.Test1)
    .then(tc.Test2)
    .then(tc.Test3);

testClass.js:

"use strict";


const Promise = require("bluebird");

let testClass = function(dbg) {

let self = this;

self._dbg = dbg;



};

testClass.prototype.printTestMessage = function() {

    let self = this;

    return new Promise(function(resolve) {

        self._dbg.printDebug(3, "testClass - printTestMessage", "start printing...");

        setTimeout(function() {

            self._dbg.printDebug(3, "testClass - printTestMessage", "finished printing...");
        resolve();

        }, 2000);

    });

};


testClass.prototype.Test1 = function() {

    let self = this;

    return new Promise(function(resolve) {

        self._dbg.printDebug(3, "testClass - Test1", "start printing...");

        setTimeout(function() {

            self._dbg.printDebug(3, "testClass - Test1", "finished printing...");
            resolve();

        }, 2000);

    });

};


testClass.prototype.Test2 = function() {

    let self = this;

    return new Promise(function(resolve) {

        self._dbg.printDebug(3, "testClass - Test2", "start printing...");

       setTimeout(function() {

            self._dbg.printDebug(3, "testClass - Test2", "finished printing...");
            resolve();

        }, 2000);

    });

};


testClass.prototype.Test3 = function() {

    let self = this;

    return new Promise(function(resolve) {

        self._dbg.printDebug(3, "testClass - Test3", "start printing...");

        setTimeout(function() {

            self._dbg.printDebug(3, "testClass - Test3", "finished printing...");
            resolve();

        }, 2000);

    });

};




module.exports = testClass;

Any help on how to stick in each function to the class reference?


Solution

  • Found it on my own: Each new Promise has to add .bind(self) at the end.

    eg:

    testClass.prototype.Test3 = function() {
    
        let self = this;
    
        return new Promise(function(resolve) {
    
            self._dbg.printDebug(3, "testClass - Test3", "start printing...");
    
            setTimeout(function() {
    
                self._dbg.printDebug(3, "testClass - Test3", "finished printing...");
                resolve();
    
            }, 2000);
    
        }).bind(self); //<-- this is the important part
    
    };