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

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

I am encountering an issue where my express.js server is not successfully processing the data sent from my react native

I have set up an API object in React Native with the following code: import axios from "axios"; import AsyncStorage from "@react-native-async-storage/async-storage"; const instance = axios.create({ baseURL: "localhost url here&q ...

Running "react-script build" is causing an issue when trying to deploy to Heroku

Struggling with deploying create-react-app on Heroku within a Node/Express server. The heroku postbuild script is throwing an error related to react-script build. As a frontend developer new to backend, I lack knowledge about Heroku deployments. ...

Client-side validation with jQuery is a powerful tool for enhancing

I am working on validating a .aspx form using the jQuery Validate plugin. I have created a validation function that includes rules for checking and messages to display error messages. Despite adding all required plugins and calling the necessary functions ...

Issue with Adding Additional Property to react-leaflet Marker Component in TypeScript

I'm attempting to include an extra property count in the Marker component provided by react-leaflet. Unfortunately, we're encountering an error. Type '{ children: Element; position: [number, number]; key: number; count: number; }' is n ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

Exploring the use of a customizable decorator in Typescript for improved typing

Currently, I am in the process of creating TypeScript typings for a JavaScript library. One specific requirement is to define an optional callable decorator: @model class User {} @model() class User {} @model('User') class User {} I attempted ...

Node.js implementation for routing WebSocket requests from an HTTPS server to an HTTP server

I'm currently developing a Node.js proxy server that handles routing requests from a website to a local endpoint. The website has the capability to run either on a local server or in a cloud instance, so the proxy needs to be able to support both HTTP ...

Converting JSON to PNG format using FabricJS

An image has been created and saved as fabricjs-json. Here is the link to the image: https://i.sstatic.net/7Wrhd.png Below is the json representation of the image: { "version": "5.2.1", "objects": [ { ...

Can you point out the distinctions between a web server and a development server?

Currently, I am in the process of expanding my create-react-app project to include a backend using express. I came across a tutorial that discusses the concept of running two servers concurrently. This has sparked some confusion for me - what sets a web s ...

Utilizing Arrays for Angular Data Binding with AJAX

I am currently experimenting with loading Ajax data into an array and then binding the array using Angular. Here is my code (I have some experience with KO, so I'm keeping it simple for now): Update: I managed to get it working. I believe the issue w ...

What is the process for connecting an event to the <body> element in backbone.js?

Could it be done? For example, like this: ... interactions { 'click button' : 'performAction' } ... ...

Enabling Cross-Origin Resource Sharing (CORS) for multiple origins in

I've encountered a problem while trying to enable multiple cors with Node in my Express API. I have managed to make it work, but now I am facing two challenges. When using Postman, I am unable to connect to my API because the origin sent from Postma ...

Prevent IonContent from scrolling to the bottom or top when using Ionic framework

In my Ionic app, I have a long text page with 2 buttons that trigger the actions scrollToBottom and scrollToTop. Due to the length of the page, I have set the scroll duration to be 30 seconds. I am facing two issues here: How can I stop the scrolling ...

How does the "deliver_order" function retrieve the value of the name parameter?

function take_order(name, callback1) { console.log("order has been taken."); callback1(name); } function prosess_order(name, callback2) { console.log(`prosesing order for ${name}.`); callback2(name); } function deliver_order(name) { console.log ...

Trouble with ES6 Arrow Functions, Syntax Error

I am encountering an issue with my JS class structure: class Tree { constructor(rootNode) { this._rootNode = rootNode; rootNode.makeRoot(); } getRoot() { return this._rootNode; } findNodeWithID(id) ...

Add a parameter to an npm script command

My npm script is set up as follows: "scripts": { "example": "webpack-dev-server --content-base examples/embeddable/" }, I am trying to create the --content-base argument dynamically based on the input when running the npm script. For example, I want ...

The forEach method in JavaScript seems to work asynchronously

After reviewing other discussions on this platform, it seems that the general agreement is that forEach should be synchronous and block. However, in my code, something appears to be off as it doesn't behave that way: var noDupes = false; // se ...

Optimal Placement of CSS and index.html Files in ReactJS with Redux

Currently, my setup for the index.html file looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pra ...

Invoking a React function repeatedly (every second)

Currently, I am working with React and utilizing Material UI to create a modal. The modal is rendered as part of the body of the code, placed at the bottom of the page. Its visibility is controlled by the state; if it's open or closed. However, I&apos ...