If I need to call 3 http API in sequential order, what would be a better alternative to the following code:
http.get({ host: 'www.example.com', path: '/api_1.php' }, function(res) { res.on('data', function(d) { http.get({ host: 'www.example.com', path: '/api_2.php' }, function(res) { res.on('data', function(d) { http.get({ host: 'www.example.com', path: '/api_3.php' }, function(res) { res.on('data', function(d) { }); }); } }); }); } }); }); }
Synchronous methods: Synchronous functions block the execution of the program until the file operation is performed. These functions are also called blocking functions. The synchronous methods have File Descriptor as the last argument.
With synchronous requests, your client application sends a request to NetSuite, and the client waits until the request is processed and a response is returned. That is, the application does not proceed with other work until receiving the response.
js docs puts it, blocking is when the execution of additional JavaScript in the Node. js process must wait until a non-JavaScript operation completes. Blocking methods execute synchronously while non-blocking methods execute asynchronously.
Using deferreds like Futures
.
var sequence = Futures.sequence(); sequence .then(function(next) { http.get({}, next); }) .then(function(next, res) { res.on("data", next); }) .then(function(next, d) { http.get({}, next); }) .then(function(next, res) { ... })
If you need to pass scope along then just do something like this
.then(function(next, d) { http.get({}, function(res) { next(res, d); }); }) .then(function(next, res, d) { }) ... })
I like Raynos' solution as well, but I prefer a different flow control library.
https://github.com/caolan/async
Depending on whether you need the results in each subsequent function, I'd either use series, parallel, or waterfall.
Series when they have to be serially executed, but you don't necessarily need the results in each subsequent function call.
Parallel if they can be executed in parallel, you don't need the results from each during each parallel function, and you need a callback when all have completed.
Waterfall if you want to morph the results in each function and pass to the next
endpoints = [{ host: 'www.example.com', path: '/api_1.php' }, { host: 'www.example.com', path: '/api_2.php' }, { host: 'www.example.com', path: '/api_3.php' }]; async.mapSeries(endpoints, http.get, function(results){ // Array of results });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With