0

I'm using Q package for an async call:

let loadPromise = Q.nfcall(m.loadObj,data);

m is an instance of this class:

class Base {

    constructor() {
        this._name = null;;
    }

    loadObj(data) {
        this._name = data;              
    }
}

The issue is that this is undefined after entering loadObj method.

As mentioned in Q wiki:

If you are working with methods, instead of simple functions, you can easily run in to the usual problems where passing a method to another function—like Q.nfcall—"un-binds" the method from its owner. To avoid this, you can either use Function.prototype.bind

How can I bind the right context to loadObj method ?

ohadinho
  • 6,894
  • 16
  • 71
  • 124
  • 1
    `let loadPromise = Q.nfcall(m.loadObj.bind(m), data);` – raina77ow Sep 21 '16 at 17:46
  • `loadObj` is not a [node-style callback function](https://github.com/kriskowal/q/wiki/API-Reference#interfacing-with-nodejs-callbacks) at all, it's not even asynchronous! You cannot use `nfcall` here! – Bergi Sep 21 '16 at 19:09
  • @Bergi you right. I've just read it in the docs: "If you're working with functions that make use of the Node.js callback pattern, where callbacks are in the form of function(err, result), Q provides a few useful..." – ohadinho Sep 22 '16 at 04:06

1 Answers1

0

As Q's doc states - you can use ninvoke to avoid un-binding like this:

let loadPromise = Q.ninvoke(m, 'loadObj', data);

Apparently, you can also do re-binding here:

let loadPromise = Q.nfcall(m.loadObj.bind(m), data);
Stas Parshin
  • 1,458
  • 1
  • 16
  • 21