Skip to content Skip to sidebar Skip to footer

Syntax And Methods For Placing Callbacks In Nodejs

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(j

Solution 1:

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);
        }
    });
});

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);
});

(untested code).

Post a Comment for "Syntax And Methods For Placing Callbacks In Nodejs"