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


const upsertAll = async (types) => {
  let jobs = [] => {
    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`);

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

Read more here:

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: