Skip to content Skip to sidebar Skip to footer

Synchronized Multiple Api Calls

I need to fetch the data from two different API endpoints, and after both data is fetched I should do something with those data (ie. compare the data from two sources). I know how

Solution 1:

I'd suggest using the request-promise module which returns promises that represent the async operations and you can then use Promise.all() to track when both of them are done and then access their results:

const rp = require('request-promise');

functiongetJSON(options) {
    returnrp(options).then(body => {
        returnJSON.parse(body);
    });
}

let options1 = {
    host: "api.mydata1.org",
    port: 8080,
    path: "/data/users/3",
    method: "GET"
};

let options2 = {
        host: "api.mydata2.org",
        port: 8080,
        path: "/otherdata/users/3",
        method: "GET"
};

Promise.all([getJSON(options1), getJSON(options2)]).then(results => {
    // process results hereconsole.log(results[0]);      // from options1 requestconsole.log(results[1]);      // from options2 request
}).catch(err => {
    // process error hereconsole.log(err);
});

You can read about Promise.all()on MDN. There are lots and lots of articles and tutorials about promises in general on the web. Here's one. They are standard in ES6 Javascript and have been available for years in ES5 through libraries. They are the chosen scheme in the Javascript language for managing or coordinating asynchronous operations. If you're doing any async programming in Javascript (which pretty much all node.js programming does), then you should learn promises.

Post a Comment for "Synchronized Multiple Api Calls"