Express res.write 不等待一系列 promise 完成

代码

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();
});

我要等待所有的promise一个一个的完成(顺序就像一个系列的方式)
然后我要快递发送第二条响应消息并结束

但它不起作用,所有 res.write() 消息都在同时打印,而 Promise 尚未完成

我也试过包装

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

upsertAll(filter).then(() =>{}) 块中但它不起作用

相关主题 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

相关话题 2 https://dev.to/afifsohaili/dealing-with-promises-in-an-array-with-async-await-5d7g

mystiquec 回答:Express res.write 不等待一系列 promise 完成

试试 for 循环

xmlns:xct="http://xamarin.com/schemas/2020/toolkit"

<Entry Text="{Binding RoutePath}"
       IsEnabled="{Binding Simulate,Converter={xct:InvertedBoolConverter}}"/>

const upsertAll = async (types) => {
  let jobs = []
  for (let i = 0; i < types.length; i++) {
    const element = types[i];
    if (type == "1") jobs.push(asyncFunction1)
    if (type == "2") jobs.push(asyncFunction2)
    if (type == "3") jobs.push(asyncFunction3)
  }
  const end = await Promise.all(jobs);
  return end
}
本文链接:https://www.f2er.com/63348.html

大家都在问