Perform an update followed by a removal操作

I've been facing a persistent issue that has been troubling me for quite some time now. The setup involves a database in MariaDB (using WAMP) and an API in ExpressJS. Within the database, there are two tables: "menu" and "item," with a foreign key relationship on the menu.

My goal is to update all items and set the foreign key field to null before deleting the menu. However, the update process is not completing quickly enough, causing complications when trying to delete the menu concurrently.

I attempted solutions using Promise and async/await, but neither approach provided sufficient wait times. Any suggestions or ideas on how to resolve this issue?

Here is my code snippet without async/await:

(router.delete('/delete/:menuId', function (req, res, next) {
  return Item.findAll({
      where: {
        menuId: req.params.menuId,
      },
    })
    .then(
      itemsFounded => {
        //Unlink items / menu
        itemsFounded.forEach(element => {
          element.update({
            menuId: null
          })
        });
        //Then destroy menu
        Menu.destroy({
          where: {
            id: menuId
          }
        }).then(() => {
          return res.status(200);
        }).catch((err) => {
          console.log(err);
          return res.status(400);
        })
      }
    )
    .catch((error) => {
      console.log(error);
      res.status(400).send(error)
    });
});)

And here is the code with async/await implementation:

(router.delete('/delete/:menuId', async function (req, res, next) {
  return Item.findAll({
      where: {
        menuId: req.params.menuId,
      },
    })
    .then(
      async itemsFounded => {
        //Unlink items / menu
        const result = await getResult(itemsFounded, req.params.menuId);
        if (result === true) {
          console.log("Result is true")
          return res.status(200);
        } else {
          console.log("Result is false")
          return res.status(400).send("error");
        }
      }
    )
    .catch((error) => {
      console.log(error);
      res.status(400).send(error)
    });
});

async function getResult(itemsFounded, menuId) {
  console.log("In getResult");
  const result = await destroyMenu(itemsFounded, menuId);
  console.log("Result of destroyMenu : " + result);
  return result;
}

... [Similar structure for other async functions]

The console output will display detailed log information about the execution process and any errors encountered.

Answer №1

If you are using a forEach loop and conducting asynchronous updates within it, the code will move on to the next statement without waiting for the updates to complete.

To resolve this issue, consider using a traditional for-loop with async/await:

async function updateItems(itemsFound) {
  for(const foundItem of itemsFound) {
    await foundItem.update({
      menuId: null
    })
  });
}

Another option is to utilize Promise.all() if you prefer parallel execution over sequential:

async function updateItems(itemsFound) {
  return Promise.all(itemsFound.map(foundItem => foundItem.update({ menuId: null}) );
}

In either case, remember to await the updateItems function when calling it:

// ... find items
await updateItems(...);
// ... delete menu

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

Develop a cutting-edge application using React, Node, and deploy it seamlessly

I'm fairly new to this and I've created a React frontend and Node backend application that I'm trying to deploy in Docker. However, I'm encountering an error mentioning Python and issues with Couchbase installation. Can someone please a ...

When utilizing Node, POST requests cannot be successfully passed using the pipe method

My custom node/express proxy implementation is experiencing an issue where POST requests are not being piped properly, while GET requests work perfectly: var pipeToTrustedZone = function(req, res){ getEnrichedHeaders(req,function(err, headers){ r ...

Receiving an error stating that .startsWith() is not a function in react native

I'm having trouble searching for items using a search bar. The original items are in 'prod', but I keep encountering errors such as 'startsWith() is not a function' and sometimes '.toLowerCase() is not a function'. const ...

Creating a custom type for accepted arguments in a Typescript method

Below is the structure of a method I have: const a = function (...args: any[]) { console.log(args); } In this function, the type of args is any[]. I am looking to create a specific type for the array of arguments accepted by this method in Typescript. ...

Ensure that at least one checkbox is selected by using custom validation in jQuery

My form has checkboxes for gender (male and female) and a set of checkboxes for days of the week (Monday to Sunday). I need to set validation rules so that at least one gender and one day is selected. Below is my jQuery code: $(document).ready(function( ...

How can I selectively import the "reboot.scss" file from bootstrap using npm in my project?

For a simple playground project, I've set up my environment with just Bootstrap (installed with npm install bootstrap) and the SCSS compiler package (installed with node install node-sass). At this point, all I need is the code from reboot.scss. I wa ...

How to retrieve a form submission from Jquery HandsonTable in PHP using $_POST

Recently, I've started diving into the world of javascript/jquery/ajax. My current project involves fetching data from a jQuery handsonTable () and integrating it with my PHP code. The process includes generating a table from a MySQL database, utili ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

"Is it possible to generate a Keystone list object without the need for an

Can a Keystone List (Model) item be created without the initial dialog? I am looking to create the item directly on the detail page, with required fields like Files and TextArray that would not function properly in a dialog. I have attempted to set init ...

What could be causing my input box to act strangely when users attempt to input information?

I seem to be facing an unusual issue with the <input onChange={this.handleArticleId} value={this.props.articleIdValue} placeholder="article id"/> field. Whenever I try typing something, the letter only appears in the input box after clicking on the s ...

When using a file uploader to set an image on v-model in Vue JS, it sometimes results in

I am currently using Vue JS 2 to develop an image uploader functionality. The input in question has a change function that triggers a function and sets the selected file to the v-model property. After logging the data, I noticed that only an empty object ...

Button color changes upon submission of form

Can anyone help me figure out how to change the color of a submit button after a form submission using Twitter Bootstrap 3? I have a form with multiple buttons serving as filters for my product page, but I can't seem to change the color of the selecte ...

Executing a function while adjusting a range slider

Having an <input type="range"> element on my website presents a particular challenge. To handle changes in this element, I am using the following function: $("#selector").bind("change", function() { //perform desire ...

Tools for parsing command strings in NodeJS

Currently, I'm utilizing SailsJS for my application. Users will input commands through the front-end using NodeWebkit, which are then sent to the server via sockets. Once received, these commands are parsed in the back-end and a specific service/cont ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Resetting dynamic form changes in Vue.js explained

Currently, I am using a template like this: <div> <div v-for="(item, key) in items" :key="key"> <div> <input type="text" :value="item.title"> </div> ...

Leveraging variables from views.py in JavaScript

My approach to populating a user page has evolved. Initially, users would choose a value from a drop-down and an AJAX call would retrieve data. Here is the code that was functioning: HTML: <h3>Experimenter: {{ request.user }}</h3> <h3>R ...

Show JSON array items

My php file (history.php) generates a JSON object $i=1; $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10"); while($rs=mysql_fetch_array($q)){ $response[$i] = $rs[&ap ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...