Node.JS async.parallel不会等待所有任务完成 [英] Node.JS async.parallel doesn't wait until all the tasks have completed
问题描述
我正在使用 aync.parallel 并行运行两个功能.这些功能要求RSS提要.然后解析RSS feed,并将其添加到我的网页中.
但是由于某些原因,async.parallel
在不等待两个函数完成之前运行回调方法
任务完成后,结果将传递到最终结果 作为数组回调.
我的代码.
require('async').parallel([ function(callback) {
fetchRss(res, bbcOpts); // Needs time to request and parse
callback();
}, function(callback) {
// Very fast.
callback();
} ], function done(err, results) {
if (err) {
throw err;
}
res.end("Done!");
});
实际上我只有完成!"在我的网页上.为什么?
我为什么需要打电话给res.end()
?
必须在每个响应上调用方法response.end().
如果我不调用它,我的网页将被下载"(我的意思是浏览器地址栏中的进度条).
我假设您的fetchRss
函数是异步的:稍后执行,并立即调用回调.您应该将回调发送到fetchRss
:function fetchRss(res, bbcOpts, callback) {
doSomething();
callback();
}
require('async').parallel([ function(callback) {
fetchRss(res, bbcOpts, callback); // Needs time to request and parse
}, function(callback) {
// Very fast.
callback();
} ], function done(err, results) {
if (err) {
throw err;
}
res.end("Done!");
});
在旁注中,应调用res.end()
,以便Node知道消息已完成并且所有内容(标题+正文)均已编写.否则,套接字将保持打开状态,并将永远等待另一条消息(这就是浏览器显示进度条的原因:它不知道请求已结束).
I am using aync.parallel to run two functions in parallel. The functions request RSS feeds. Then the RSS feeds are parsed and added to my web page.
But for some reason async.parallel
runs the callback method without waiting until the two functions have completed
Once the tasks have completed, the results are passed to the final callback as an array.
My code.
require('async').parallel([ function(callback) {
fetchRss(res, bbcOpts); // Needs time to request and parse
callback();
}, function(callback) {
// Very fast.
callback();
} ], function done(err, results) {
if (err) {
throw err;
}
res.end("Done!");
});
In fact I only have "Done!" on my web page. Why?
Why do I need to call res.end()
?
The Node.JS documentation says:
The method, response.end(), MUST be called on each response.
If I don't call it, my web page will be being "downloaded" (I mean a progress bar in the address line of my browser).
I suppose your fetchRss
function is asynchronous: is is performed later and the callback is immediately called. You should send the callback to fetchRss
:
function fetchRss(res, bbcOpts, callback) {
doSomething();
callback();
}
require('async').parallel([ function(callback) {
fetchRss(res, bbcOpts, callback); // Needs time to request and parse
}, function(callback) {
// Very fast.
callback();
} ], function done(err, results) {
if (err) {
throw err;
}
res.end("Done!");
});
On a side note, you should call res.end()
in order for Node to know that the message is complete and that everything (headers + body) has been written. Otherwise, the socket will stay open and will wait forever for another message (which is why the browser shows a progress bar: it doesn't know that the request has ended).
这篇关于Node.JS async.parallel不会等待所有任务完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!