用于将回调放置在nodej中的语法和方法 [英] syntax and methods for placing callbacks in nodejs
问题描述
我使用快捷库在nodejs中有以下http端点:
I have the following http endpoint in nodejs using the express library:
app.get("/api/stocks/lookup/:qry", function(req, res) {
getJson(lookupSearch(req.params.qry), function(json) {
var quotes = [];
und.forEach(json, function(d) {
getJson(quoteSearch(d.Symbol), function(j) {
quotes.push(j);
});
});
res.send(quotes); //how can I make this execute after the .forEach is finished?
});
});
这里, getJson
看起来像这样: / p>
Here, getJson
looks like this:
var getJson = function(search, cb) {
http.request(search, function(response) {
var raw = '';
response.on('data', function(d) {
raw += d;
});
response.on('end', function() {
cb(JSON.parse(raw));
});
response.on('error', function(err) {
console.error(err);
});
}).end();
};
我看到为什么这不会作为http请求 getJson
是异步的,因此 res.send(quotes)
将立即发回。那么,如何在 forEach
循环完成后发送 res.send(quotes)
我可以在 forEach
函数上附加回调吗?
I see why this won't work as the http requests inside getJson
are asynchronous and so res.send(quotes)
will be sent back almost immediately. So, how can I get res.send(quotes)
to be sent after the forEach
loop is complete. Can I attach a callback onto a the forEach
function?
总之,
- 如何在
forEach $ c后使用
res.send(quotes)
$ c>循环完成。 - 可以附加回调(例如在
forEach
循环后执行的回调)到对象?我可以附加回调到什么?要清楚,对我的回调的想法意味着事件循环将在其中附加回调的函数/对象完成执行之后调用它。
- How can I use
res.send(quotes)
after theforEach
loop is complete. - Is it possible to attach callbacks (such as a callback to be executed after the
forEach
loop) onto objects? What can I attach callbacks to? To be clear, the idea of a 'callback' to me means that the event loop will call it after the function/object in which the callback is attached to is finished executing.
感谢所有的帮助!
推荐答案
将getJson转换为promise将是一个好主意,因为承诺是很好的合作。没有promise,手动的方式是保持未完成请求的计数器:
Converting your getJson into a promise would be a good idea, as promises are nice to work with. Without the promises, the manual way is to keep a counter of outstanding requests:
var outstanding = 0;
json.forEach(function(d) {
outstanding++;
getJson(quoteSearch(d.Symbol), function(j) {
quotes.push(j);
if (!--outstanding) {
res.send(quotes);
}
});
});
如果你按promise的方式,你会做一个 code> over
json
,并返回请求的承诺;你可以在promise数组上指定然后
。如果你使用jQuery而不是你自己的自制解决方案,例如
If you did go the promises way, you would make a map
over json
, and return the promise of the request; you could then specify a then
over the array of promises. If you used jQuery instead of your own homebrew solution, for example,
var requests = json.map(function(d) {
return $.getJSON(quoteSearch(d.Symbol), function(j) {
quotes.push(j);
});
});
$.when(requests).then(function() {
res.send(quotes);
});
(未测试的代码)。
这篇关于用于将回调放置在nodej中的语法和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!