Utilizing the Google Geocode API to handle a promise with a substantial array

My Objective

To efficiently process a large array using the .map method and interact with the Google Geocoder API through promises to get location data.

The goal is to utilize Promise.all to store results in a .json file upon completion of the operation.

This code is specifically designed for node, where the array has a structured format of [[key:value],[key:value],....]


Implementation Details

var foo = (function() {
  let promises = airports.map(function(airport) {
    return geocoder
      .geocode(airport[1])
      .then(function(res) {
       let x = {
          ident: airport[0],
          address: res[0].formattedAddress,
          lat: res[0].latitude,
          long: res[0].longitude
        };
        return x;
      })
      .catch(function(err) {
        console.log(err);
      });
  });
  return Promise.all(promises)
    .then(function(promises) {
      console.log("promises resolved");
      fs.writeFile(
        path.join(__dirname, "/airports.json"),
        JSON.stringify(promises),
        "utf-8",
        function(err) {
          if (err) throw err;
          console.log("Done!");
        }
      );
    })
    .catch(function(err) {
      console.log(err);
    });
})();

The Challenge

The current implementation works well with small arrays but encounters issues when dealing with larger datasets. It seems to be related to rate limiting from the api, resulting in many ETIMEDOUT errors after processing a few hundred records.

I am exploring ways to slow down the iteration process, perhaps by executing one request per second. How can I incorporate this delay while handling multiple promises effectively?

Implementing a delay could potentially reduce the occurrence of ETIMEDOUT errors during the execution.

Thank you for your assistance.

Answer №1

To regulate the flow of requests, only one request is allowed per second

var foo = (function() {
    var delay = 1000; // defines the rate
    return airports.reduce((promise, airport) => promise
        .then(results => new Promise(resolve => setTimeout(resolve, delay, results)))
        .then(results => geocoder
            .geocode(airport[1])
            .then(function(res) {
                let x = {
                    ident: airport[0],
                    address: res[0].formattedAddress,
                    lat: res[0].latitude,
                    long: res[0].longitude
                };
                return results.concat(x);
            })
            .catch(function(err) {
                console.log(err);
            })
        ), Promise.resolve([])
    ).then(function(promises) {
        console.log("promises resolved");
        // ... etc
    })
})();

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

Verify if the radio element is marked as selected in the AJAX reply

My ajax response contains two radio elements and I need to check if they are checked in the response. I've tried using the code below to check the radio status but it's not working: $('#input[type=radio]').each(function(){ alert($( ...

What is the best way to showcase and retrieve the data within a structure array in MATLAB?

As a first step, I prompt the user to input their own text files containing information about states, capitals, and populations. This data is then stored in a structured array using the following code: clear clc %Part A textfile=input('Please enter t ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Storing the information filled out in the form and utilizing it to navigate to the correct destination URL

With the generous assistance and insightful advice from members of Stack Overflow, I am nearing completion of my quiz project. However, I do have a few lingering questions regarding some final touches needed for the project. Before delving into those quest ...

Creating a dropdown menu in Bootstrap 5 without using any of the Bootstrap

In my Angular application, I have a header with icons and pictures that I would like to use as dropdown menus. The code snippet for this functionality is shown below: <li class="nav-item dropdown"> <a class="nav-li ...

In the world of React in Meteor, the command event.preventDefault() doesn't seem

I have encountered an issue with my application development. I am utilizing a submit form in Meteor with React, and although I am using event.preventDefault(), the page continues to reload every time the submit button is clicked. Following a brief delay, i ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

The React popup window refuses to close on mobile devices

I am currently facing an issue with a site (a react app) deployed on GitHub pages. The site features cards that, when clicked on, should open a modal/dialog box. Ideally, clicking on the modal should close it. However, I have encountered a problem specific ...

The behavior of JavaScript replace varies between Chrome and IE

This JavaScript code successfully replaces a string in Chrome: myUrl = someUrl.replace('%2C%7B%22itn%22%3A%5B%22%20guidelines%20%22%5D%7D', ''); However, when tested in Internet Explorer, it does not replace the string as expected. T ...

Merge two arrays of objects in Ramda.js based on their shared ID property

I'm working with two arrays of objects: todos: [ { id: 1, name: 'customerReport', label: 'Report sent to customer' }, { id: 2, name: 'handover', label: 'Handover (in C ...

Tips for displaying Ajax response in a modal popup

I have a link that, when clicked, sends an AJAX request and successfully receives a response in the form of an HTML file, which I then append to a div. However, I want to display this div as a modal popup and I have attempted the following: In the HTML fi ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...

What methods can be utilized to enhance the visual appeal of a threejs model

I'm currently working on enhancing the visual quality of my 3D models, aiming for smoother edges and more realistic shadows. To achieve this, I am experimenting with an OBJ file format. Here's the code snippet I'm using to load and display t ...

Exploring Django with Selenium: How to Extract Page Content Using find_element

I have been attempting to extract the text 'Incorrect Credentials' using selenium. Here is what I have experimented with... message_text = self.driver.find_element(By.XPATH, '//*[@id="toast-container"]/div/div[1][@class="ng-binding toast-t ...

Type of flow: customizable prop types for React components that can be extended

In the scenario where a SelectOption component is present, with props defined as: type OptionType = { +id: string, +label: string, } type Props = {| +options: OptionType[], +onItemPress: OptionType => void |} I intentionally left the OptionType ...

Using jQuery to create a Select All Checkbox that toggles a specific class

I have come across similar examples in the past, but I have been unable to make it work as intended. The examples I found only use standard checkboxes. I attempted to customize the checkbox using a sprite sheet by applying a class, but I am struggling to a ...

Generate HTML on the fly using Node variables

Utilizing Node.js with Express as the server, I have implemented a feature where users can upload .CSV files containing data. This data is then parsed and stored in a main array made up of arrays, with each line representing one array element. Currently, I ...

Automatically appending textarea value in HTML tag upon form submission via JQuery

When a form is submitted through JQuery, the HTML tag automatically adds textarea value. This is my JQuery code: $('#calling').click(function() { $('#myform').submit(); }); Within my form, there is a textarea element: <textar ...

Issue: mongoose.model is not a valid function

I've been diving into several MEAN tutorials, and I've hit a snag that none of them seem to address. I keep encountering this error message: Uncaught TypeError: mongoose.model is not a function Even after removing node_modules and reinstalling ...

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...