Pregunta

I'm really struggling with the Q module in nodejs.

This is my code below. It works fine on runnable.com but when I put it in one of my controller methods (as is), it just keeps waiting and I can tell its invoked the first method. but it just keeps waiting. What am I doing wrong. I've already spent 2 days on this now :(

var Q = require('q');

function Apple (type) {
    this.type = type;
    this.color = "red";

    this.getInfo = function() {
        console.log(this.color);
        return;
    };
}

var apple = new Apple('macintosh');
apple.color = "reddish";

var stat = Q.ninvoke(apple, 'getInfo').then(function() { console.log(err) });

Update:

Changed Q.ninvoke to Q.invoke and using v2.0 of Q, this is no longer available. I get the error invoke is undefined.

Changed to using v1.0 of Q and now the following works just fine.

var Q = require('q');

function Apple(type) {
    this.type = type;
    this.color = "red";

    this.getInfo = function() {
        return this.color;
    };
}

var apple = new Apple('macintosh');
apple.color = "reddish";

Q.invoke(apple, 'getInfo')
    .then(function(color) {
        console.log(color);
    })
    .fail(function(err) {
        console.log(err);
    });
¿Fue útil?

Solución

Q.ninvoke, expects a Node.js style method. Node.js style methods accept a callback function and that function will be invoked with the error or with the result of the execution.

So, your program will work, if you can change your getInfo function to accept a callback function and invoke it when the result has to be returned, like this

var Q = require('q');

function Apple(type) {
    this.type = type;
    this.color = "red";

    this.getInfo = function(callback) {
        return callback(null, this.color);
    };
}

var apple = new Apple('macintosh');
apple.color = "reddish";

Q.ninvoke(apple, 'getInfo')
    .then(function(color) {
        console.log(color);
    })
    .fail(function(err) {
        console.error(err);
    });

Note: Since you are not using Node.js style method, you should use Q.invoke instead of Q.ninvoke like this

var Q = require('q');

function Apple(type) {
    this.type = type;
    this.color = "red";

    this.getInfo = function() {
        return this.color;
    };
}

var apple = new Apple('macintosh');
apple.color = "reddish";

Q.invoke(apple, 'getInfo')
    .then(function(color) {
        console.log(color);
    })
    .fail(function(err) {
        console.log(err);
    });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top