What is the best way to invoke an API two times, passing different parameters each time, and then merge both responses into a single JSON object using a callback function?

This code snippet is currently functional, but it only retrieves the JSON response for the first set of parameters.

I am looking to make multiple calls to an external API with different parameters and then combine all the responses into one concatenated JSON response.

While I have two sets of parameters in this code, ideally I would like to have around 200. Any assistance on achieving this would be greatly 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((resolve, reject) => {
        const callback1 = function(data) {
            // console.log(data);
            // res.send(data);
            resolve(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};

Answer №1

If you need to handle multiple asynchronous tasks and wait for them to complete, you can utilize Promise.all. Consider a scenario where you have an array of request parameters:

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

You can then use [].map along with Promise.all, returning the promise in your function like this:

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

    // Here we assume that the library being used lacks error handling
    const promises = requests.map(data => new Promise(resolve => {
        search.json(data, resolve);
    }))

    // This promise will be resolved once all individual promises are resolved
    return Promise.all(promises);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing highlight.js for seamless integration with vue2-editor (Quill)

I am having trouble connecting vue2-editor (based on quill) with highlight.js Despite my efforts, I keep encountering an error message that reads: Syntax module requires highlight.js. Please include the library on the page before Quill. I am using nu ...

What is the best way to combine two arrays and generate a new array that includes only unique values, similar to a Union

Here are two arrays that I have: X = [ { "id": "123a", "month": 5, "markCount": 75 }, { "id": "123b", "month": 6, "markCount": 85 ...

Should each of them be opened in a new connection if web and worker processes are separated?

In my current NodeJS web app project, there are two processes in play - a web process and a worker process. These processes communicate via AMQP. To start the application, I run two scripts: one for the web process called server.js, and another for the wor ...

"Learn how to use pure JavaScript to show the output of a PHP file on a webpage

I created a basic PHP file named hello.php that shows a 'hello world' message as follows: <?php echo "Hello world!"; ?> Now, I am looking to store this message in a JavaScript variable. How can I achieve this? <script type="tex ...

Issues with loading an external CSS file in an HTML document

I've been attempting to implement a loading animation using jQuery, but I'm encountering issues with loading the CSS file. I have tried various paths for the css file such as: <link href="css/animation.css" type="text/css" rel="stylesheet"> ...

Having trouble getting the Pokemon modal to show both the type and image?

HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My First JS App</title> <lin ...

Ways to retrieve nested data from an object

I have added an object with categories in a database. It displays the price and date of addition. How can I output the date to the console? Currently, in the console, it shows: [ [ { cost: '50$', date: [Object] } ] ]. I need to extract the inform ...

PHP is struggling to interpret the JSON object

I am struggling to pass the username and password to a PHP script and verify them in the database. To achieve this, I utilize the following client-side script to create a JSON object and send it to the PHP file. var myobj = {}; myobj["usrname"]= $( "#cust ...

The casting operation failed because the type '_InternalLinkedHashMap<dynamic, dynamic>' cannot be converted to type 'String'

Looking for assistance on how to correctly send a nested JSON object to an API using HTTP in Dart. Below is the code snippet I have been working with: Map m = { "email": '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Having trouble sending data from the controller to the view in Laravel 8

I am struggling to display data retrieved from the database in my view through the controller. Despite trying various solutions found on similar questions, none of them seem to be effective. My main goal is to showcase a list of employees on my admin page. ...

Connect directly to the DOM without using an event

A jQuery function is included in my code: $('#big-bad-bold-button') .on('click', aloha.ui.command(aloha.ui.commands.bold)); This function binds the click event. Is there a way to achieve the same binding without requiring a click? ...

Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation: { "name": "Some unique name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, ...

Service Worker Tips: Caching the initial page with dynamic content

I have a single-page application with a dynamic URL generated using a token, for example: example.com/XV252GTH, which includes various assets such as CSS and favicon. This is how I implement the Service Worker registration: navigator.serviceWorker.regist ...

I am having trouble getting my ajax call to save data in the database despite no PHP or console errors appearing. What could be

I am attempting to create a rating system where users can rate from 1 to 5 stars, and then the average rating will be displayed. To accomplish this, I am utilizing Ajax, jQuery, PHP, MySQL, and HTML. Below is the basic code with the script and simple htm ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

What methods can I use to sort content by its rating?

I am embarking on my inaugural project and attempting to construct a product filtering system. So far, I have successfully implemented search and category filters; however, configuring the rating filter has proven to be challenging. Here is an excerpt of ...

Instructions for appending an id to the URL of events in fullcalendar using Rails

Looking for a way to attach an ID to the URL of a fullcalendar event in a Rails application? I am using a json.jbuilder file: json.array!(@estudiante.clases) do |clase| json.extract! clase, :id json.id clase.id json.title clase.name json.start cl ...

How can we access parameters in ag-Grid's Angular 1 onFilterModified event?

Currently, I am incorporating grid options using the code snippet provided below: var gridOptions = { columnDefs: columnDefs, rowData: null, enableFilter: true, onFilterChanged: function() {console.log('onFilterChanged');}, onFilterModified: fun ...

Differentiating the texture of a pointCloud in three.js shaderMaterial: A step-by-step guide

Utilizing THREE.PointCloud for optimum performance, I aim to animate 100,000 objects. However, I am facing an issue with setting different textures for particles. How can I incorporate uniforms with various textures in this code? Is it possible to pass s ...

Grab all the text using Java Jsoup

I am having an issue with the code I have written. The doc.body.text() statement is not displaying the text content within the style and script tags. I examined the .text() function code and found that it searches for all instances of TextNode. Can someone ...