how can we make a call asynchronously through nodejs

Not applicable

I have to build a mashup service in which i am making total of 6calls parallely.Through JS it wont be the best way to do it.

How can i achieve it through nodejs,I am new to this nodejs

Any example where anyone has done asynchronous calls through nodejs,Please share

Thanks

0 3 339
3 REPLIES 3

phanim
New Member

You can use Node JS community tools like "nimble" which help to perform multiple related tasks in sequence, in parallel and help to implement other useful and tricky scenarios.

http://caolan.github.io/nimble/

Not applicable

Hi @shubham singh, welcome to Apigee Community!

The following is a snippet of a Node.js API Proxy making parallel calls using Promises.

app.get('/albums', function (req, res, next) {
  try {

    // get an array of promises of artists. Each artist to be passed as: e.g. artists[]=radiohead&artists[]=phoenix
    Promise.all(req.query.artists
        .map(function (artist_name) {
          return getAlbum(artist_name);
        }))
      .then(function (all_artists) {

        //convert each resolved promised into JSON and convert it into an array.
        res.json(all_artists.map(function (artist) {
          return JSON.parse(artist)
        }));
      })
  } catch (e) {
    res.send(e.message);
  }
});

// this is the function that makes the call to the backend. Note usage of request promise
function getAlbum(artist) {
  var options = {
    uri: 'http://lyrics.wikia.com/api.php',
    qs: {
      artist: artist,
      fmt: 'json',
      action: 'lyrics'
    }
  };
  return rp(options);
} 

Try this tutorial to learn step-by-step how to build this API Proxy and some foundations about JavaScript Promises.

https://github.com/dzuluaga/apigee-tutorials/tree/master/apiproxies/parallel-nodejs-api-proxy-with-p...

Hope it helps!

thanks it is very descriptive and clean code. My requirement is little different though much on same lines. can you please share some thoughts

- In addition to "artist" that is passed as response, I want to insert "id" in response also when i aggregate and send the response along with other fields see the contract below. Basically some tweak before json.parse call.

{
	"12": {
		"Response": "Success",
		"StatusCode": 200,
		"artist": {
			"title": "Shipping Cost",
			"body": ""
		}
	},
	"13": {
		"Response": "Success",
		"StatusCode": 200,
		"artist": {
			"title": "Shipping Cost",
			"body": " "
		}
	},
	"14": {
		"Response": "Error",
		"StatusCode": 404,
		"ErrorMessage": "Content Not Found"
	}
}

- Also i want to count the array req param values and if they are greater than 10 then send a response error message and not process anything.

Please share your thoughts.

thanks,

Aakash