Executing promises in a for-loop within a setTimeout function

Looking to integrate a web API with JavaScript/AngularJS 1.x on a timed interval due to rate limiting. The code provided attempts to achieve this by utilizing a list of objects called RecordList and a function called setDelay that introduces delays with the setTimeout method.

The issue arises when attempting to determine if all promises within the setTimeout function have been successfully resolved. Traditional methods such as Promise.all and $q.all don't work seamlessly in conjunction with setTimeout. Any suggestions for an alternative approach?

var waitInterval = 300;
var promiseArray = [];

function setDelay(obj, s) {
  setTimeout(function() {
    var SomePromise = $http.post('odataURI', obj).then(function success(result) {
      //resolve(result);
    });
    promiseArray.push(SomePromise);
  }, waitInterval * s);
}
for (var s = 1; s <= RecordList.length; s++) {
  setDelay(RecordList[s - 1], s);
}

Answer №1

If you want to run the next promise after one has finished, consider using a recursive function.

function postData(num) {
  return Promise.resolve(num);
}

function addDelay(num, milliseconds) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
       postData(num).then(function(response) {
        resolve(response);
      });
    }, milliseconds)
  })
}

function iterateList(list, delay = 1000, index = 0, results = []) {
  addDelay(list[index], delay).then(
    function(response) {
      console.log(response);
      results.push(response);
      if (index == list.length - 1) {
        console.log('Results: ', results); // Additional logic can be added here
        return results;
      } else {
        return iterateList(list, delay, index + 1, results);
      }
    }
  ); 
}

var dataList = [1, 2, 3, 4, 5];
iterateList(dataList);

Answer №2

If you want to achieve the same result, consider using `async` and `await` in your code.

const waitInterval = 300;
const promiseArray = [];

async function LoopFunction() {
  let dataMain;
  for (let s = 1; s <= RecordList.length; s++) {
     dataMain = await setDelay(RecordList[s - 1], s); // You will receive the data after consuming the API successfully.
  }
}

function setDelay(obj, s) {
 return new Promise((resolve, reject) => {
   setTimeout(() => {
     const SomePromise = $http.post('odataURI', obj).then(result => {
       resolve(result);
     });
    }, waitInterval * s);
 }); 
}

I hope this solution is beneficial for you.

Answer №3

Even without using recursion, it is still possible to achieve the desired outcome.

var interval = 300;
var promises = [];
var tickCount = 0;

function setDelay(obj, s) {
  setTimeout(function() {
    var somePromise = Promise.resolve(obj);
    somePromise.then(function success(result) {
      tickCount++;
      console.log(result);
      if (tickCount === RecordList.length) {
          Promise.all(promises).then((res) => {
            console.log(res);
          });
      }
    });
    promises.push(somePromise);
  }, interval * s);
}

var RecordList = [1,2,3,4,5];

for (var s = 1; s <= RecordList.length; s++) {
  setDelay(RecordList[s - 1], s);
}

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

I am in search of sample cases demonstrating the process of incorporating a throbber while pages are

Is there anyone who can provide a code snippet demonstrating how to implement an animated throbber during the loading of an asp.net page? I would greatly appreciate multiple examples if possible. ...

How to use JQuery to deselect a checkbox

Having trouble unchecking a checkbox? In my HTML (PHP) code, I have the following: <div class="row"> <div class="col-md-12 pr-1"> <label>Modele</label> <div class="form-group"> <div class=" ...

Trigger the angular $exceptionHandler in the Chrome console

Currently, I am customizing the default $exceptionHandler, following a similar approach to what is demonstrated on Angular's official website: https://docs.angularjs.org/api/ng/service/$exceptionHandler. It has been functioning effectively. Nonethele ...

Is there a way to transfer a value from one JS function to another in Node.js?

I am struggling to retrieve the return value from a JavaScript function in Node.js and pass it back in a POST method within my server file. Despite my efforts, I keep receiving an undefined result. What could be causing this issue? My objective is to retur ...

What is the process for sending a successful status code to the front end using node.js?

Lately, I've delved into using node.js as the backend for my projects. While I have managed to successfully post data to the database, I'm currently stuck on notifying the front-end about the successful data save. Below is my user route code, wit ...

Having trouble getting the onClick event to trigger in React?

I have a button in my navbar that triggers a submenu (list of items) to display when clicked. Each item is a separate child component and I want them to trigger an event when clicked. However, the onClick event listener does not seem to be working. Other m ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...

What is the sequence of Javascript Execution for the event of window.location.href?

After browsing through this discussion on asynchronous JavaScript location.href call and watching a video explaining the event loop, I found no clear explanation regarding the behavior of href within window.location: The script order in the source code is ...

Updating eventKey Text in React-Bootstrap: A Step-By-Step Guide

Having some trouble changing the text on a selected dropdown button. I'm struggling to figure out how to access it, any assistance would be greatly appreciated. Thank you. return ( <DropdownButton bsStyle={title.toLowerCase()} title={title} key= ...

Controlling the Output in Typescript without Restricting the Input

I am interested in passing a function as a parameter, allowing the function to have any number of parameters but restricting the return type to boolean. For example, a function Car(driver: Function) could be defined where driver can be ()=>boolean or ( ...

What is the best method to create Promise API synchronously?

When it comes to testing with NodeJS, I rely on selenium-webdriver. My goal is to streamline the selenium-webdriver API by making it synchronous, which will result in more concise tests. The method getTitle() is used to retrieve the title of the current p ...

I stored a nested object in sessionStorage, but when I retrieve and parse it, I receive string values

Is it possible to return a complete object without having to parse each level repeatedly after parsing my object? Have I stored my data incorrectly using redux-persist? For instance, when I have a login form that sends credentials to the server and receiv ...

Eliminate apostrophes in a string by using regular expressions

Can someone help me with this word What is The Answer? I need to eliminate the space and apostrophe '. To remove spaces, should I use this method: data.text.replace(/ +/g, ""). But how can I remove the apostrophe? ...

Unable to store multiple users in MongoDB

Currently, I am encountering an issue with passportJS not saving more than one user to MongoDB while using nodeJS with the expressJS server framework. Initially, I successfully set up email registration with passport-local. However, when I added passport- ...

External IPs cannot access Node.js

I am facing an issue with my Amazon EC2 Server where I have set up a node js server. It is not accessible from the outside using the public DNS, but it can be accessed from the same instance (localhost). Any assistance in resolving this problem would be gr ...

What is the best way to change a String into an Array within MongoDB?

I need help with converting the type of an object that has been changed. Is there a way to transform this: { "_id" : NumberLong(257), "address" : "street Street, house 50, appartment 508, floor 5" } into this: { "_id" : NumberLong(257), "userAddres ...

Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly. AJAX function <script type="text/javascript> var stopTime =0; var scoreCheck = function () { $.ajax({ url: "<?php echo 'http:// ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

Building an Image/Grid system using CSS and Javascript

Currently in the process of constructing a fresh website, I find myself in need of a solution to a particular issue (specifically involving PHP, MySQL, and Zurb Foundation). The challenge at hand is to fashion an image comprised of 1,000,000 pieces, each ...

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...