Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
How can call an api twice (with different parameters each time) with a callback, and return two different responses combined together in json?

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};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!