Async calls the template for the API in Node.js

Creation of my first "serious" Node.js project (using Express).

I need to use several calls for several REST APIs, collect all the results, massage them and return the full JSON to the client (HTML5 + AJAX).

  • Call API A
  • Call API B
  • Call API A again (with results from B)
  • The result of a process of 3 calls in JSON
  • response.send (result)

I am sure / hope that there will be a simple template, or a solution, or a module that I just didn’t use Google correctly :) I would also appreciate an opinion on where to place such operations (in the "routes" section, "Individual files " etc.).

Thank you for your time!

+8
asynchronous express
source share
2 answers

The async module is suitable for this kind of work. In particular, you can use the async.waterfall function.

Example:

async.waterfall([ function(callback){ callback(null, 'one', 'two'); }, function(arg1, arg2, callback){ callback(null, 'three'); }, function(arg1, callback){ // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' }); 

Edit, if you have some non-trivial dependencies between jobs, you can use async.auto . It will determine the best working order of functions based on their requirements.

+8
source share

There are many control flow libraries. I used Q in my previous projects, which I have no complaints about, however, I will probably deal with using the async caolan library for my next project.

https://github.com/caolan/async

From what you described above, you probably want to look at using a parallel function

https://github.com/caolan/async#parallel

The problem you described can be easily transferred to a parallel example in documents

EDIT: I missed a bit about API dependencies. Whenever you need to pass values ​​in a chain and control the order, you need to use the waterfall method (see qiao answer). If there is a case where the calls are independent, you should use the parallel method. Example parallel method below

 async.parallel({ google: function(callback){ http.get("http://www.google.com", function(res){ console.log("google done"); callback(null, res.statusCode); }) }, yahoo: function(callback){ http.get("http://www.yahoo.com", function(res){ console.log("yahoo done"); callback(null, res.statusCode); }) } }, function(err, results) { if(!err){ console.log("all done"); console.log(results.google); console.log(results.yahoo); }else{ console.log(err); } } ); 

It does all your queries in parallel and gives you a callback when all this is done. Here you will massage your data.

List of control flow libraries:

https://github.com/joyent/node/wiki/Modules#wiki-async-flow

+2
source share

All Articles