对于使用 q 模块在 node.js 中使用延迟 promise ,我有一些不理解的地方。这是一个说明我的问题的设置。
var Q = require('q');
var http = require('http');
var url = 'http://www.genenames.org/cgi-bin/download?' +
'col=gd_hgnc_id&' +
'col=gd_pub_eg_id&' +
'status=Approved&' +
'status_opt=2&' +
'where=&' +
'order_by=gd_pub_eg_id&' +
'format=text&' +
'limit=&' +
'submit=submit';
httpGet = function (url) {
var deferred = Q.defer();
var body = "";
http.get(url, function(res) {
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
// WE NEVER GET HERE ...
console.log(body);
deferred.resolve(body);
});
})
.on('error', function(err) {
console.log(err);
});
return deferred.promise;
};
var fetchData = function() {
var deferred = Q.defer();
httpGet(url)
.then(deferred.resolve())
.done();
return deferred.promise;
};
fetchData()
.then(function() {
console.log("I got here before data was downloaded!")
process.exit(0);
})
.catch(function(err) {
throw(err);
})
.done();
在 fetchData 中,“.then”函数在 httpGet() 完成数据下载之前被调用。我不明白为什么在调用 deferred.resolved 之前执行 .then。
如果我在 fetchData() 中注释掉 deferred.resolve(),那么事情会按我预期的那样工作,当然程序会挂起,因为最终的 promise 永远不会实现。
有人能指出我哪里出错了吗?
最佳答案
您正在立即调用 deferred.resolve
。相反,您想将该函数的引用传递给 then
,如下所示:
.then(deferred.resolve)
关于node.js q 不等待延迟 promise 被解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29662917/