There are several libraries that can help you organize the execution of asynchronous code. Async is the one I use and eachSeries () is useful here:
function search(x,callback) { dns.resolve(x, function (err, addresses) { if (!err) { res.send("bad"); } else { res.send("good"); } callback(err); }); } async.eachSeries(queries, function(query,callback) { search(query,callback); }, function(err) { if(err) { console.log("we had an error"); } } );
Note that Async will call the final callback as soon as one of the iterations has an error, so if you don't want to dwell on it, you need to call callback() in search() instead of callback(err) .
UPDATE (without using a library):
If you do not want to use the library, you can implement it like this:
function searchInternal(queries, idx, callback) { if(idx === queries.length) { callback(); return; } dns.resolve(queries[idx], function (err, addresses) { if (!err) { res.send("bad"); } else { res.send("good"); } searchInternal(queries, idx+1, callback); }); } function searchAll(queries, callback) { searchInternal(queries, 0, callback); } searchAll(queries, function() { console.log("all done now"); });
Please note: this code is not tested and probably not the best implementation, but therefore we use libraries.
source share