Home > Software design >  How can call an api twice (with different parameters each time) with a callback, and return two diff
How can call an api twice (with different parameters each time) with a callback, and return two diff

Time:07-12

The below code is currently working but only brining back the first parameters JSON response.

I would like to be able to call this external API a few times with different parameters and combine the responses back in one concatenated JSON response.

I have two sets of parameters that I'm using in this code but I will really would have more like 200 ideally. Any help is appreciated.

const SerpApi = require('google-search-results-nodejs');
const search = new SerpApi.GoogleSearch("674d023b72e91fcdf3da14c730387dcbdb611f548e094bfeab2fff5bd86493fe");
const handlePictures = async (req, res) => {
    const params1 = {
        q: "kevin durant",
        tbm: "isch",
    };
    const params2 = {
        q: "lou williams",
        tbm: "isch",
    };
    return new Promise((rs, rj) => {
        const callback1 = function(data) {
            // console.log(data);
            // res.send(data);
            rs(data);
        };

        // Show result as JSON
        search.json(params1 , callback1);
        // how do I get this to work too? ---->  search.json(params2, callback1);
        // res.end();
    })
};

module.exports = {handlePictures};

CodePudding user response:

You can wait for multiple asynchronous jobs to complete using Promise.all. Let's say you have an array of request parameters:

const reqs = [
  { q: 'request one', tbm: 'isch' },
  { q: 'request two', tbm: 'isch' },
  { q: 'request three', tbm: 'isch' },
]

Then you could use [].map and Promise.all, and return that promise in your function.

const handlePictures = (req, res) => {
    const reqs = [
        { q: 'request one', tbm: 'isch' },
        { q: 'request two', tbm: 'isch' },
        { q: 'request three', tbm: 'isch' },
    ];

    // unfortunately the library you're using has no error handling
    const promises = reqs.map(data => new Promise(resolve => {
        search.json(data, resolve);
    }))

    // this promise resolves when all given promises are resolved
    return Promise.all(promises);
};
  • Related