Terminate an asynchronous function

Currently, there is an express server running on Node.js where clients can create tasks that involve various processes such as cycles and database communication.

The communication between the client and the server is facilitated through socket.io. I am looking for a way to implement a feature that allows the client to cancel or terminate a task manually.

I have attempted to use child_process for this purpose, and while it works correctly, it creates separate processes that consume around 50MB of RAM each due to the necessary libraries. With potentially hundreds of tasks running simultaneously, this could become a significant issue.

To start a task, the client can trigger the following function:

socket.on('tasks:launch', (collect) => {
 (async () => {
   await collector_obj.tasks.task(uid, data, io);
 })();
});

To stop a task, the client should be able to execute the following function:

socket.on('tasks:stop', (collect) => {
   // code to kill the function goes here
});

For testing purposes, a sample task function is provided below:

task: async (uid, data, io) => {
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
    while(1) {
        await sleep(1000);
        console.log(Date.now());
    }
}

Answer №1

One way to incorporate a canceling mechanism into the async..await syntax is by explicitly implementing support for it, with the widely recognized approach being through the use of AbortController.

To effectively manage and interact with multiple tasks, it is essential to maintain a task pool or list. For scenarios where terminating all tasks is required, a simple method could look like this:

const tasks = {
  controllers: new Set(),
  add() {
    const controller = new AbortController();
    this.controllers.add(controller);
    const abortPromise = new Promise((resolve, reject) => {
      controller.signal.onabort = () => reject(new DOMException('', 'AbortError'));
    });

    try {
      while(1) {
        await Promise.race([sleep(1000), abortPromise]);
        await Promise.race([sleep(2000), abortPromise]);
      }
    } finally {
      this.controllers.delete(controller);
    }
  },
  removeAll() {
    for (const controller of this.controllers)
      controller.abort();
    this.controllers.clear();
  }

The tasks.removeAll function can be invoked using tasks.stop. Further optimization may be possible if sleep() inherently supports cancellation and can receive the current controller instance.

Although ES promises don't have built-in support for cancellation, and async..await enforces the usage of native promises, integrating cancelable promise implementations such as p-cancelable requires foregoing some syntactic conveniences. In such cases, maintaining a list of cancelable promises instead of controllers could prove beneficial.

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 generates parallel instances of mysql connections and fails to terminate them afterwards

I am currently working on a project that involves using loopback, node, and MySQL to make parallel database calls. Even though there is already a persistent connection established between node and MySQL, when these parallel calls are executed, new connecti ...

Nodejs installation failure detected

I am dealing with a package node and I am looking to install it using the following command: ./configure --prefix=/path/NODEJS/node_installation && make && make install However, when I run this command, it returns the error below: File ...

Delay the rendering of the fetching component until the fetch operation is completed

My task is to retrieve data for SSR and send that data from the Client. const MyPage = ({ myFetch1, myFetch2, myFetch3, }) => { const dispatch = useDispatch(); dispatch(doSomething1(myFetch1)); dispatch(doSomething2(myFetch2)); dispatch(do ...

Creating blank entities with app.post using AngularJS and mongoose in a node.js environment

My issue seems to be with my REST API as it is posting empty objects. The value I am retrieving from req.body.name appears correctly when I log it using console.log(req.body.name);. POST: { name: 'typing any name', status: null } typing any na ...

Launching ReactJS and ExpressJS on Nginx server

I am currently running an Ubuntu VPS setup (version 20.04LTS) with Nginx Server installed. Within the setup, I have two separate local repositories - one for front-end ReactJS code and another for back-end ExpressJS code. To run the ExpressJS code, I will ...

Issues with MongoDB queries failing in live environments due to authentication problems

I'm currently developing a NodeJS application using Mongoose for database operations. Initially, I had no issues accessing my records in the "bears" database when authentication was disabled in Mongoose. However, upon enabling authentication and conf ...

iisnode - Error on IIS 7.5: 405 Method not permitted during PUT request execution

I've been diving into iisnode and expressjs to create a REST-like API using node. In my server.js file, I set up something like this: app.put("/test", function(req, res){ ... }); However, when I send a PUT request, I keep getting a 405 ...

Executing asynchronous actions with useEffect

Within my useEffect hook, I am making several API requests: useEffect(() => { dispatch(action1()); dispatch(action2()); dispatch(action3()); }, []); I want to implement a 'loading' parameter using async/await functions in the hook ...

Issue encountered while attempting to start React and Node.js: NPM error

I've encountered some errors in my Node.js and React.js project. I have a server and a React SPA, both working independently. When I use "concurrently" to start them together, I get the following errors: [0] npm ERR! missing script: servernpm run clie ...

Tips for accessing the status of every request to a single API using Node.js

I am looking to retrieve the status of an API server using nodejs. I have set up a nodejs interface with the endpoint "api/request?connId=50&timeout=90". This particular API will maintain the request for the specified time on the server's end. Upo ...

What type of data does a router function return?

What is the recommended return type to exit a router function explicitly in order to avoid excessive else blocks and deep indentations? app.get("/xx", function(req, res) { if (c1) { res.render("c1"); // What should be returned here? } ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...

Utilize Express efficiently by requiring modules only once for multiple routes within the application

Here is an overview of my project directory structure: MyProject -app.js -routes -routeone -routetwo In the app.js file, I have the following setup: var express = require('express'); var app = express(); var routeone = ...

Having trouble making POST requests with the request module in node.js?

I am currently working on sending data to a Java back end running on a Tomcat server. Here is what I have attempted so far: I have already installed the request module and found that the GET method is functioning correctly. Router.post('/', func ...

Creating a multi-tiered RESTful API using Node.js and Express

Currently, I am utilizing node.js express for constructing a straightforward rest API. I have already created an API like this: app.get('/sites/:site/:building/:floor',function(req,res){ var building = req.params.building, floor = req.params ...

Enhanced efficiency in the interaction between front-end JavaScript and back-end JavaScript

As a frontend developer, I find myself in the unique position of working on a project that involves processing a large amount of data in my nodeJS backend (while using reactJS for the front end). After the necessary data processing is completed in the bac ...

Managing uncaught exceptions in node.js

While working on my project, I encountered an issue with catching exceptions when opening a connection using mongoose.createConnection. Here's the code snippet causing the problem: var createdDb = mongoose.createConnection(connectionString); createdD ...

Verify whether an email is already registered in firestore authentication during the signup process using Angular

When a user signs up for our app, I want them to receive immediate feedback on whether the email they are attempting to sign up with already exists. Currently, the user has to submit the form before being notified if the email is taken or not. This desire ...

Express.js does not recognize the req.query value

Incorporating Stripe Checkout functionality into a MERN application has been the focus of my recent project. Upon successful payment by a customer, they are directed to a checkout success URL where the CheckoutSuccess page is displayed. Additionally, Stri ...

The reason for the failure of npm install in Express.js is due to an issue with getaddrinfo E

For the past two years, I have been running a Node.JS / Express.JS server-side program inside a Node.JS docker container without any issues. However, recently upon installation, it started throwing a strange error. I typically use docker-compose to install ...