Send response and continue to perform tasks Express | Node.js

If your job is not super-CPU-intense and you can tolerate some work on the main server thread, then just use await to break the execution so that the request can be properly sent. You can use setTimeout or await.

// This line is wrong too - ask a separate question if needed
var requestTime = Date.now; 

app.post('/messages', async function (req, res) {
  console.log("received request");

  // handle the response
  var body = res.body;
  res.status(200).send({ success: true });
  console.log("sent response");

  // Method 1:
  await performComplexTasks(body)

  // Method 2:
  setTimeout(() => performComplexTasks(body), 0);
})

async function performComplexTasks(body){
   // The line below is required if using the `await` method -
   // it breaks execution and allows your previous function to
   // continue, otherwise we will only resume the other function after
   // this function is completed.
   await new Promise(resolve => setTimeout(resolve, 1));

   // perform data with body data here;
   console.log("finished tasks:", Date.now()-requestTime, "ms");
}

This isn’t really a fantastic solution and you’d need to use worker threads for long operations.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)