我使用快捷库在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?
总之,
感谢所有的帮助!
推荐答案将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中的语法和方法
发布评论