[英]Q async library with node.js waiting
我真的在nodejs中的Q模塊上苦苦掙扎。
這是我的下面的代碼。 它在runnable.com上可以正常工作,但是當我將其放在一個控制器方法中(按原樣)時,它一直處於等待狀態,我可以告訴它調用的第一個方法。 但它一直在等待。 我究竟做錯了什么。 我已經花了兩天了:(
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) });
更新:
將Q.ninvoke更改為Q.invoke並使用Q v2.0,該功能不再可用。 我得到錯誤調用未定義。
更改為使用Q的v1.0,現在以下工作正常。
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);
});
Q.ninvoke
需要一個Node.js樣式方法。 Node.js樣式方法接受一個回調函數,該函數將在錯誤或執行結果時被調用。
因此,如果您可以將getInfo
函數更改為接受回調函數並在必須返回結果時調用它,則程序將正常工作,如下所示
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);
});
注意:由於未使用Node.js樣式方法,因此應使用Q.invoke
而不是Q.ninvoke
這樣
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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.