What is the best way to exit a for loop within a promise?

let ingredientsArray = savedata.ingredients.split(',');    
for(let i = 0; i < ingredientsArray.length; i++){

      let data = {
            content_name: ingredientsArray[i],
            dogFoodId: dogId
      }
      db.dog_ingredients.create(data).then(function(result){

      }, function(error){
            console.log(error);

            res.status(403).send('Error');
            //stop the loop at this point

      });
    }

Is there a way to stop a for loop in a promise?

I am working on a project using Node.js with Express and Sequelize.

Answer â„–1

Before the initial then callback is triggered, the loop will have already completed. This is one of the promises' guarantees if the create operation returns a proper promise rather than just a thenable that completes asynchronously.

To sequentially add ingredients (one at a time), you can utilize the reduce trick; any promise rejection during this process will skip the remaining ingredients:

savedata.ingredients.split(',').reduce(function(p, ing) {
    return p.then(function() {
        var d = {
            content_name: ing,
            dogFoodId: dogId
        };
        return db.dog_ingredients.create(d);
    });
}, Promise.resolve())
.catch(function(e) {
    console.log(e);
    res.status(403).send('Error');
    return Promise.reject(e);
});

The code may appear lengthy due to comments and object initialization, but it can also be simplified as follows (if rejection propagation is not necessary):

savedata.ingredients.split(',').reduce(function(p, ing) {
    return p.then(function() {
        return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId });
    });
}, Promise.resolve())
.catch(function(e) {
    res.status(403).send('Error');
});

(While it's possible to further minimize the code, I prefer maintaining readability for easier debugging—leave minification to tools designed for that purpose.)


If adding ingredients in parallel is preferred, the code would be simpler:

Promise.all(savedata.ingredients.split(',').map(function(ing) {
    return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId });
}).catch(function(e) {
    res.status(403).send('Error');
    return Promise.reject(e);
});

(Assuming there is no need to propagate the rejection in this case.)

However, keep in mind that this approach involves parallel processing.

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 you effectively load shared header and panel HTML onto pages located in separate directories using jQuery Mobile?

I am currently developing a multi-page application utilizing jQuery Mobile and incorporating loadPage() to retrieve various pages. The overall structure is outlined below. landing.html /app-pages/page1.html /app-pages/page2.html /app-pages/page3.html ...

Calculating the quantity of choice elements within a dropdown menu using jQuery

Is there a way to calculate the number of <option> elements in a <select> element using jQuery? <select data-attr="dropdown" id="input1"> <option value="Male" id="Male">Male</option> <option value="Female" id="Female"& ...

Is there a way to eliminate the # sign from hash data using jQuery?

Can anyone help me retrieve the hash value from the URL? var hash = window.location.hash; I am looking for a way to remove the "#" sign from the hash. Any suggestions? ...

Vuetify's Handy Helper Classes

Hey everyone, I'm working on a vuetify project and I need to convert inline styles to utility classes (if possible) font-size: 24px; font-weight :600 I checked the documentation and noticed that it only provides options for setting size and weight wi ...

Blazor compatibility issue with Bootstrap 5 carousel functionality

Check out the link below to view a carousel that is functioning with the help of jquery and bootstrap 4.3.1 (code lines 48,50). I attempted to switch to using Bootstrap 5 JS files for the carousel, but it did not work as expected due to issues with code li ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

Utilize axios to fetch specific documents based on named route parameters in Express

I'm struggling with the communication between my frontend and backend when making a specific GET request. On the frontend, I am using React in combination with an express/mongoose setup on the backend. To make the GET call in the frontend, I am usin ...

Having issues with retrieving data using findOne or findById in Express and Node JS, receiving undefined values

Currently, I am working on a microservice dedicated to sending random OTP codes via email. Below is the code for my findbyattr endpoint: router.get('/findbyattr/:email', async (request, response) =>{ try { let requestEmail = reque ...

Stop click event from firing on a disabled tree node within an angular custom directive template

In the browser, my custom Angular tree component is displayed like this: + Parent 1 + Child 1-A - Child 1-A-A - Child 1-A-B - Child 1-A-C + Child 1-B + Child 1-C This is what the directive template looks like: <ul> &l ...

Is there a way to view the contents of the dev server once it has been bundled by webpack?

From my understanding, webpack in dev mode stores all imported files in a certain location and then serves the bundle.js file to the client. If the code inside bundle.js requests a CSS file, the css-loader should have already been configured to provide t ...

Creating a static file for deployment: A step-by-step guide

Currently, my node and webpack configuration allows me to run the dev-server and work on my application. However, I am facing issues in generating the static bundle.js file required for deployment on my website. I need help configuring my webpack.js file ...

What could be causing the Multer error in my Express.js application when attempting to upload a file for the second time, even though the first time was successful?

Whenever I try to upload a single file, the code works flawlessly. However, if I attempt to upload another file, I encounter the following Multer error: Error code: 'LIMIT_UNEXPECTED_FILE', field: 'myFile', storageErrors: [] To succes ...

The imported JS file shows a warning that the variable 'myProperty' is defined but not utilized anywhere

When I try to import a variable from the same folder, why am I getting an error message saying it is defined but not used? I am sure that I am using it. Your input would be greatly appreciated! error 'componentName' is defined but never used. ...

Error encountered while attempting to upload file via POST request due to a failed NodeJS fetch operation, with the specific issue being

I am attempting to upload a file using the native fetch function in NodeJS version 17.5 (which can be found at https://nodejs.org/ko/blog/release/v17.5.0/). Unfortunately, I am encountering the following error: TypeError: fetch failed at Object.processRes ...

Is it acceptable to exclude curly braces when declaring a function?

My current approach to declaring functions in PHP is as follows: function theFunction($theVar) { ... } Similarly, in JavaScript, I declare functions like this: function theFunction(theVar) { ... } I'm wondering if I can skip using curly brac ...

What is the correct way to test setInterval() statements within Angular?

Here is a simple code snippet I am working on: public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { ...

Revise the calculation output when a specific input is missing

As I work on creating a basic web page for computing values based on selected options, I've encountered an issue with the calculation process. The result does not immediately appear; instead, I have to input a value like 0 and then delete it in order ...

Using a $watch on a directive that has an isolated scope to monitor changes in a nested object property retrieved from

I have developed a custom directive with an isolated scope and element. I am utilizing the values passed into the directive to construct d3/dc charts. The data goes through crossfilter on the $scope so that the directive attributes can access it. Despite s ...

Discovering the method for retrieving post parameters in Node.js

I am currently utilizing Node.js with Express and the httpAsyncClient library in Android. I have sent a request to Express using Post, including parameters. The request goes through successfully, but I am unable to retrieve the parameter in Post. I have ...

"Within the node.js framework, the search/query section of the URL appears

I am currently working on a website (client + server) that both operate from the same machine. Despite not encountering any issues in Chrome's developer tools, I am struggling to identify the source of a problem. My dilemma is with trying to POST a s ...