Express res.write not waiting for array of promises to finish

code

const upsertAll = async (types) => {
  let jobs = []
  types.map(type => {
    if (type == "1") jobs.push(asyncFunction1)
    if (type == "2") jobs.push(asyncFunction2)
    if (type == "3") jobs.push(asyncFunction3)
  })
  jobs.reduce((p, fn) => p.then(fn), Promise.resolve())
}
router.get('/api/generate', async (req, res) => {
  res.write(`${new Date().toISOString()} Generating metadata. Please wait...`);
  const filter = req.query.q.split(',');
  await upsertAll(filter)
  res.write(`${new Date().toISOString()} Done`);
  res.end();
});

I want to wait for all promises to complete one-by-one (sequentially like in a series manner)
Then I want express to send the second response message and end

But its not working, all res.write() messages are printing at the same time while the promises have not completed yet

i have also tried wrapping

res.write(`${new Date().toISOString()} Done`);res.end();

in a upsertAll(filter).then(() =>{}) block but it does not work

related thread 1 res.send is not waiting for my async function to finish before sending the response to the front end on my Express server app

related thread 2 https://dev.to/afifsohaili/dealing-with-promises-in-an-array-with-async-await-5d7g



Read more here: https://stackoverflow.com/questions/68462212/express-res-write-not-waiting-for-array-of-promises-to-finish

Content Attribution

This content was originally published by Ridhwaan Shakeel at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: