PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

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

 July 25, 2022     api, asynccallback, javascript, json, promise     No comments   

Issue

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};

Solution

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);
};


Answered By - don_aman
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing