res.send 的承诺

Promises with res.send

我在 return 承诺后回复时遇到以下问题:

let emailSent = new Promise((resolve, reject) => {
    array.forEach(async (item, i, array) => {
       //asynchronous code for send emails
       if (index === array.length -1) resolve();
    }
})

emailSent.then(() => {
   res.status(201).send({
       message: 'Email sent.',
       status: 201,
   })
}

在浏览器中,响应从不 returns。 承诺后returnres.send最好的方法是什么?

在不知道您使用的确切代码的情况下,因为看起来您已经削减了很多,我怀疑您有多个异步函数调用,您正在尝试并行执行。

对于类似的事情,你应该将每个异步调用映射到一个承诺列表中,然后等待它们全部在一个承诺中解决 Promise.all(),像这样:

let emailSent = Promise.all(
    array.map(async (item, i, array) => {
       //asynchronous code for send emails
    })
});