Techniques for retrieving response values in a function while using a for loop

Looking for assistance with my code. I have a for loop that contains a setTimeout function which calls the server every second and receives a response. However, when trying to access the server response, it returns undefined. Here is my code snippet:

for (let i = 0; i <= latlng.length; i++) {
  setTimeout(function() {
    GeoCoder.geocode({
      'address': latlng[i],
    }, function(results, status) {
      if (results) {
        var lng = results[0].geometry.location.lng()
        var lat = results[0].geometry.location.lat()
      }
      console.log("are we getting location", lng + "" + lat)
    });
  }, i * 250);
}

Answer №1

Utilizing promises provides a higher level of control when managing responses over multiple iterations.

Take a look at the example below, which can be customized to emulate the desired outcome:

function performTask(value) {
return new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('within setTimeout: ' + value);
  }, 1000);
});
}

async function customFunction(){
  let num = 7;
  const result1 = await performTask(num);
  console.log(result1);
  num = 3;
  console.log('outside of setTimeout: ' + num);
}

customFunction();

Answer №2

I adjusted your code to enhance clarity and organized the API call into a distinct function. If you are utilizing the following package https://www.npmjs.com/package/geocoder, it should function correctly.

var GeoCoder = require("geocoder");

const addresses = [
  "South Road Morningside",
  "Hyde Park Shopping Centre",
  "Coachmans Crossing Cne Peter Place",
  "Watt Ave & 3rd Street",
];

const handleApiCall = index =>
  GeoCoder.geocode(addresses[index], function(err, data) {
    console.log(index);
    if (err) console.log(err);
    if (data) {
      console.log(data);
    }
  });

for (let index = 0; index < addresses.length; index++) {
  setTimeout(() => handleApiCall(index), index * 250);
}

Answer №3

To ensure the accuracy of each iteration in the loop, it is crucial to create a function closure inside the loop. This will lock in the state of the loop and prevent errors such as having 'i' equal to length + 1 when setTimeout is called after the loop has finished.

Instead of creating a closure within the loop, you can take advantage of the native argument passing feature of setTimeout. By utilizing this feature, any arguments beyond the second one will be passed to the callback function of setTimeout.

for (let i = 0; i <= latlng.length; i++) {
  setTimeout(function(i) { // <-- consume the i variable
    GeoCoder.geocode({
      'address': latlng[i],
    }, function(results, status) {
      if (results) {
        var lng = results[0].geometry.location.lng()
        var lat = results[0].geometry.location.lat()
      }
      console.log("are we getting location", lng + "" + lat)
    });
  }, i * 250, i); // <-- pass in i here as an argument to setTimeout
}

Answer №4

When utilizing the https://github.com/wyattdanger/geocoder package, it seems that the formal arguments for the callback function are reversed.

To rectify this issue, simply switch function(results, status) to function(status, results).

As of now, due to the absence of errors, the conditional branch

  if (results) { // actually testing the error argument
     // set lng and lat
  }

is not executed, resulting in lng and lat remaining as undefined since their declaration.

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

How can we efficiently assign an array of JSON responses using Observables and map within a TypeScript interface, and then display it in HTML using *ngFor in Angular 2?

export interface Relation{ name: string; address: string; dob: number; } The JSON response I received is as follows: [ {"name":"John", "address":"xyz", "dob":"2000-01-10"}, {"name":"Jamie", "address":"abc", "dob":"1990-01-10"} ] The issue seems to be wi ...

Numbering Tables Effectively in ReactJS

Currently working on coding a table in ReactJS and MUI, my goal is to number the No. column from 1 to the length of the array. This snippet shows my code: <TableBody> {quizes.map((quiz, index) => ( <TableRow key={quiz._id}> ...

Tips for utilizing Angular Js to redirect a webpage

Can someone help me figure out how to redirect to another page using Angular Js? I've searched through various questions here but haven't found a successful answer. This is the code I'm currently working with: var app = angular.module(&ap ...

What method can be used to implement an alert on a disabled asp.net drop-down menu?

I currently have a drop-down element set up like this: <asp:DropDownList ID="cboJPRem" class="jprem" runat="server"> <asp:ListItem Value="None" Selected="True" Text="None"></asp:ListItem> <asp:ListItem Value="1da ...

Guide on converting a timestamp output in Node.js

I ran a query to retrieve TimeStamp data from MYSQL using Node JS, and the output is as follows: MyDate: Thu Apr 28 2016 07:02:45 GMT+0700 (SE Asia Standard Time) Can anyone help me convert it to yyyy-mm-dd hh:mm:ss format? ...

Breaking down arrays using the JADE Template Engine

Currently, I am utilizing the JADE template engine in conjunction with ExpressJS. I am attempting to pass an array to my JADE template like so: var data = { "labels" : ["Label 1", "Label 2"] }; res.render('index', {data: data}); The struct ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

Is there a way to identify a change in the URL using JQuery?

My goal is to clear the localStorage when a user navigates to a different page. For instance, if I am currently on . When the user goes to the URL, , I want to clear the localStorage. This is my script using JQuery. $(window).unload(function(){ if ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

A guide to automatically playing audio on a webpage using HTML and JavaScript

I'm currently in the process of developing a quiz application, and my goal is to have a sound play when a user enters the webpage to initiate the quiz. Initially, I attempted to use JavaScript to trigger the sound on page load, but unfortunately, the ...

Switching the navbar image with HTML and JavaScript when clicked

Looking to change the image upon clicking on any of the navbar items. Emulating the navigation bar behavior from this website : This is my current progress : The HTML file : <html lang="en"> <head> <meta charset="utf-8" /> ...

Having trouble with React MaterialUI <ListItemSecondaryAction> getting stuck while dragging within a react-beautiful-dnd Draggable?

I am currently utilizing react-beautiful-dnd to create draggable list items with the help of Material UI ListItems. Each of my ListItems consists of a ListItemText and a ListItemSecondaryAction which acts as a target for triggering a context menu (enclosi ...

What is the best way to show an alert() when a user clicks on a marker in Google Maps?

My current setup:view image description ... google.maps.event.addListener(marker,'click',function() { this.map.setZoom(15); this.map.setCenter(marker.getPosition()); console.log('hello world'); this.presentAlert(); // ERROR co ...

Discovering the parameter unions in Typescript has revolutionized the way

My current interface features overloaded functions in a specific format: export interface IEvents { method(): boolean; on(name: 'eventName1', listener: (obj: SomeType) => void): void; on(name: 'eventName2', listener: (obj: Som ...

Bluebird Enthusiastically Predicting the Outcome of a Complex Operation

Lately, I've been heavily utilizing Bluebird in my HAPI API development. However, I've encountered a perplexing issue that has left me puzzled due to either my understanding or lack of experience. Below is an example demonstrating the challenge ...

Is there a way to retrieve the text of li elements without assigning them IDs?

I have a list of names with four items inside it. My goal is to display the text of the selected name while hiding the others. Only one name should be visible at a time on the page. <ul id="names"> <li>John</li> <li>Alex</ ...

Why is Socket.io functioning on localhost but fails to work once deployed to Heroku?

Sharing my socket server code: const io = require("socket.io")(8080, { cors: { // origin: "http://localhost:3000", origin: "https://mern-bubble.herokuapp.com", }, }); This is the client-side implementation: useEf ...

JavaScript throws an error when attempting to access an object's methods and attributes

Within my Angular.js module, I have defined an object like this: $scope.Stack = function () { this.top = null; this.size = 0; }; However, when I try to use the push method of this object, I encounter an error stating undefined: ...

Launching email client with predefined content using React Native

I'm currently utilizing an npm package for launching a mail client along with specific data. You can find the package here: https://www.npmjs.com/package/react-native-mail-compose Furthermore, I am following their provided example: import MailCompos ...

I am struggling to locate the source of this mysterious middleware error

I seem to be encountering an issue with a middleware function, resulting in a "middleware is not a function" error message. I'm at a loss as to why this is happening... [Error] TypeError: middleware is not a function Routes JS import express from &ap ...