Continuing a Sequelize transaction after a loop

I am facing an issue where the transaction in my chain of code is committing immediately after the first loop instead of continuing to the next query. Here is a snippet of my code:

        return sm.sequelize.transaction(function (t) { 
          return Room.create({
            room_type: req.body.room_type
            },{transaction: t}).then(function(roomtype){
           for (i=0;i<room.length;i++){ 
               return Roomtype.create({
                   name : req.body.roomtype[i]
                    },{transaction: t}); //the transaction is only working until here and committing after that
           }
           for  (i=0;i<another.length;i++){ //I want to continue to the second loop here
               return User.create({  
                 email :req.body.email[i]
               },{transaction:t}); 
          }
        }).then(function(result){
        }).catch (function(err){
        })
     }) 

How can I ensure that the transaction continues to the next loop after the first one?

Answer №1

Remember that once you introduce a return statement, the function will immediately end. Subsequent iterations of the for loop and the second loop will not execute. It is important to avoid returning in the middle of your loops.


If the order of transactions is not crucial, the most efficient method would be to utilize Promise.all, which handles an array of promises and provides the results once all promises are fulfilled. With your existing logic, the implementation would resemble the following:

return Room.create({ 
  room_type: req.body.room_type 
}, { transaction: t })
  .then(function (roomtype) {
    const promises = []

    for (let i = 0; i < room.length; i++) { 
      const promise = Roomtype.create({
        name: req.body.roomtype[i]
      }, { transaction: t })
      promises.push(promise)
    }

    for (let i = 0; i < another.length; i++){
      const promise = User.create({  
        email: req.body.email[i]
      }, { transaction: t })
      promises.push(promise)
    }

    return Promise.all(promises)
  })
  .then(function (results) {
    . . .
  })

To further enhance your code, consider replacing the for loops with map for a cleaner implementation:

return Room.create({ room_type: req.body.room_type }, { transaction: t })
  .then(function (roomtype) {
    return Promise.all(req.body.roomtype.map(function (type) {
      return Roomtype.create({ name: type }, { transaction: t })
    }))
  })
  .then(function (roomResults) {
    // Conduct similar actions for user creation here
  })

Alternatively, if maintaining order is crucial, you may need to implement a recursive function that processes each Promise sequentially.

const createRooms = function (transaction, types, index = 0) {
  return Roomtype.create({ name: types[index] }, { transaction })
    .then(function (result) {
      if (index < types.length - 1) {
        return createRooms(transaction, types, index + 1)
      }
      return result
    })
}

Invoke the above function within your code:

return Room.create({ room_type: req.body.room_type }, { transaction: t })
  .then(function (roomtype) {
    return createRooms(t, req.body.roomtype)
  })
  .then(function (result) {
    // Conduct similar actions for user creation here
  })

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

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...

javascript issue with attribute manipulation

My current struggle involves setting the attribute of an element through programming, but I keep encountering an error in Firebug: obj.setAttribute is not a function. Since I am working with jQuery, allow me to provide some additional code for better conte ...

Error: An unexpected token < was caught in the TypeScript Express code

Using TypeScript to compile and run an Express server that simply serves an HTML file. However, encountering an error in the response under the network tab in Chrome for app.js: Uncaught SyntaxError: Unexpected token '<' Below is the server c ...

Our system has picked up on the fact that your website is failing to verify reCAPTCHA solutions using Google reCAPTCHA V2

Error Message We have noticed that your website is not validating reCAPTCHA solutions. This validation is necessary for the correct functioning of reCAPTCHA on your site. Please refer to our developer site for further information. I have implemented the re ...

What is the optimal strategy for managing multilingual text in a React website?

As I develop a react website with multiple localizations, I am faced with the question of how to best store UI texts for different languages. Currently, I am contemplating two approaches: One option is to store text directly in the UI code, using an objec ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...

Learn how to display two different videos in a single HTML5 video player

Seeking a solution to play two different videos in one video element, I have found that only the first source plays. Is jQuery the answer for this problem? HTML Code: <video autoplay loop id="bbgVid"> <source src="style/mpVideos/mpv1.mp4" type ...

Looking to establish a connection between a Node.js server and Flutter using socket.io?

In my backend development project, I am utilizing Node.js and the Express framework. To establish a real-time connection between the server and the client (Flutter app), I will be incorporating socket.io. On the server side, I have implemented a socket.io ...

Inject the JSON data fetched through AJAX into Datatables

I have been successfully using the datatables plugin to populate multiple tables with data. However, I realized that instead of making separate AJAX calls for each table, I could optimize by fetching the data once and storing it in a variable to be used by ...

Conceal when dates align

In my events list, I have dates displayed and would like to hide any end dates that are the same as the start dates. For instance; <span class="start_date">Wed 23rd January</span> <span class="end_date">Wed 23rd January</span> I ...

It seems I am unable to retrieve req.body and the console.log function is not displaying the request object

const { render } = require("ejs"); const express= require("express"); const app = express(); const path = require('path'); app.use(express.static('views')); app.set('view engine','ejs'); ap ...

JavaScript: Transforming a key-value pair collection into an array of objects

I'm looking to convert a dictionary into a list of dictionaries using JavaScript. Can someone help me with that? var dict = { "apple" : 10, "banana" : 20, "orange" : 30 } var data = [ {"apple" : 10}, {"ban ...

What could be the reason for document.body.style.backgroundColor not working properly?

I am currently experimenting with a logic that triggers the screen to turn black upon pressing the print screen key. Despite changing the background color, it is not functioning as expected. The console has detected a change in value. What could be going ...

Encountering a Type Error with Webpack4 when running npm start

When I run `npm start` on my Vue project, everything seems okay, but when I open the browser page, it shows up blank and gives me an Uncaught error: TypeError: Cannot read property 'call' of undefined The console view displays the following e ...

Tips for sending a form and showing results without the need to refresh the page

I am currently working on developing a basic calculator that takes a user input number and displays the calculated output without redirecting or reloading the page. However, since I have no experience with JavaScript (js) and Ajax, I am seeking assistance ...

Fetching data using Axios from a specified URL

I am currently facing an issue with the npm package axios while attempting to execute a get request to a specific URL. The problem arises as I consistently receive an error code 503. Here is the snippet of code in question: let data, response; response = ...

Encountering no automatic refresh feature in Next.js

Encountering an issue with Next.js where the local host index page doesn't automatically refresh whenever a change is made. To provide some context, I initiated a Next.js application using npx create-next-app --use-npm. After starting the local serve ...

"Utilizing AJAX for real-time search to target the final

Recently, I've been playing around with the AJAX Live Search feature that can be found on this site: http://www.w3schools.com/php/php_ajax_livesearch.asp The way it transfers the input value via AJAX to a php file for comparison is quite interesting ...

What is the best way to obtain a list of all the modules that are currently accessible in AngularJS

When declaring an Angular module, I specify its dependencies as follows: const myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]); Each dependency comes with its own set of dependencies, directives, controllers, etc. Is there a way to qu ...

Do AngularJS applications function similarly to windows?

Do AngularJS apps behave like windows? And is it possible to add an event listener to them? I am currently working on a proof of concept to see if an Angular app can communicate with a server without impacting the host. One potential solution I have thou ...