Do you think this is an effective method for creating a series of promises for an array?

I'm working on inserting an array of items into an SQL server using promises for a sequential execution. To achieve this, I've come up with the following method:

const ForeachPromise = function (array, func) {
  let promise = func(array[0]);

  for (let i = 1; i < array.length; i++) {
    promise = promise.then(() => func(array[i]));
  }

  return promise;
}

The concept is that when func is called, it will return a promise which is then chained to the previous promise.

...
return ForeachPromise(type.subprocessen, function(subproces) {
    return newSubproces(subproces, typeId, dienstId, createData, s + 1);
});

I haven't tested this code yet, but I believe it should work as intended. However, my main concern is whether I am correctly using promises. Promises can be tricky and prone to misunderstanding, so I want to ensure that I haven't made any major mistakes.

Answer №1

Absolutely, that strategy is sound and particularly effective when working with promises. Just a couple of minor points to consider:

  • Be sure to account for the scenario where the array is empty. Kick off your chain using Promise.resolve() (a promise that resolves with undefined) and initiate your loop at index 0.
  • Since the callback within the then function is async, the value of your i variable may not be what you expect - this is known as the traditional loop closure issue.

Employing the .reduce method address both of these concerns effectively:

function foreachPromise(array, func) {
  return array.reduce(function(promise, elem, i) {
    return promise.then(function() { return func(elem) });
  }, Promise.resolve());
}

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

A guide to accessing the sibling of each selector with jQuery

Imagine you have the following HTML structure: <div class="parent"> <div class="child"></div> <div class="sibling">content...</div> </div> <div class="parent"> <div class="child"></div> <div ...

What is the best way to include keys in my JSON data, rather than just values?

I've encountered an issue with the PrimeVue datatable I created, as it is only showing empty rows. After investigating, I believe the problem lies in my JSON data structure, where the fields do not have keys. What modifications should be made to stan ...

Guide to clearing the application cache for a particular page within a Single Page Application

In our Angular and MVC project, we have implemented two pages - an Online page and an Offline page in a Single Page Application (SPA) setup. The Offline page should load when the network connection is lost, and an error should be displayed when trying to a ...

MeteorJS and Coffeescript team up to deliver unexpected results

I'm currently facing an issue while trying to utilize the Email.send() feature in the Meteor email package. I seem to have hit a roadblock with the following code snippet: Email.send ({ from: '<a href="/cdn-cgi/l/email-protection" class=" ...

The Vuetify navigation drawer seems to have a quirk where it only closes after an item

I am brand new to Vue and struggling to figure out why my vue v-navigation-drawer is not working properly. It is located in app-root.vue and was initially closing when clicking on a drawer item, but now requires two clicks to close. After the first click, ...

The iPhone webview keyboard causes the layout to be pushed upward and remain elevated

While editing text fields, the native keyboard pops up and stays visible in the webview. It's almost like leaving the toilet seat up! Is there a way to return to the original scroll position after the native keyboard disappears? Perhaps an event that ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

Is it still relevant to use ng-repeat track by in AngularJS 1.6?

Is using track by in Angular 1.6 with ng-repeat still considered beneficial? Does it contribute to better performance? ...

What is the most efficient method for transferring session data from a Client component to a server component in NEXT.js version 13 and beyond?

Currently, I am working on a web application that requires passing session?.user?.email from the useSession() function in next-auth/react to a server-side component. This server-side component will then execute a fetch request to /api/users/email/ to deter ...

Assign an Angular model to an input in a dynamic manner

Currently, I am working on developing a compact spreadsheet feature for my angular application. My goal is to replicate a common functionality found in spreadsheets where users can click on a cell and then modify its value using a larger input field at the ...

jquery is unable to locate text

UPDATE: I have recently implemented a function that calculates and displays the length of a certain element, but it currently requires user interaction to trigger it: function check() { alert($("#currentTechnicalPositions").html().length); } After s ...

Is there a way to control the quantity of items being displayed in my ng-repeat directive?

Here are the objects in my array: 01-543BY: Array[1] 03-45BD23: Array[1] 03-67BS50: Array[1] 06-78FR90: Array[1] 07-467BY3: Array[1] 09-23DF76: Array[1] Currently, I have a total of six objects, but I only want to display four. This is how I am using ng- ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

Is it necessary to have async Javascript XMLHttpRequest automatically set the request header for XMLHttpRequest?

I recently implemented a small async GET request to my server using vanilla JavaScript. var rReq = new XMLHttpRequest(); rReq.onload = function (e) { window.updateCartnRows(e.target.response); }; rReq.open('GET', &apo ...

Unable to apply inline styles to React Component

My Carousel component is supposed to return a collection of carousel boxes, each styled with a specific property. However, I am facing an issue where the style property is not being applied to the returning divs. How can I resolve this? I noticed that whe ...

A configuration for ".node" files is missing: specifically, the loader for node_modules/fsevents/fsevents.node in a project using Vite

Everything was running smoothly in my Vite + React project until last week when out of nowhere, I encountered this error: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node node_modules/fsevents/fsevents.js:13:23: 1 ...

What could be causing the lack of population in ngRepeat?

In my angular application, I encountered an issue with ngRepeat not populating, even though the connected collection contains the correct data. The process involves sending an http get request to a node server to retrieve data, iterating over the server&a ...

Is it possible to utilize WebRTC (simple-peer) with STUN without the need for additional signaling?

I am currently exploring the utilization of the simple-peer library to create browser-to-browser WebRTC connections through data channels. My understanding, although it may be flawed, is that for two browsers to establish a connection via WebRTC, they need ...

Submitting Forms with XMLHttpRequest

I'm trying to utilize XMLHttpRequest in order to retrieve the response from a remote PHP file and showcase it on my webpage. The issue I'm facing is that the form's data isn't being submitted to the remote PHP page. Any suggestions on ...

Image not appearing when sharing on Facebook

I've been trying to create a Facebook share button using the Javascript SDK, and here is the code I have been utilizing: $(function() { $('.facebook-share').click(function(e) { e.preventDefault(); FB.ui({ method: 'feed& ...