提问者:小点点

如何在地图中获得所有promise,其中有超时


我正试图从一张有超时的地图中得到所有的结果。

我尝试使用promise.all(),但由于使用了setTimeout函数,没有成功。

我会很高兴,如果有人可以看看哦,我的代码,并建议如何做正确的。

非常感谢。

new Promise(async (resolve, reject) => {
  Promise.all(
    items.map(async (item, i) => {
      await setTimeout(async () => {
        return await SendMail(item);
      }, 5000 * i);
    })
  ).then((mailsRes) => {
    resolve(mailsRes);
  });
});

共2个答案

匿名用户

只需循环浏览您的项目,并在发送每封电子邮件后休眠x秒(本例中为5秒)。

const sleep = (milliSeconds) => {
    return new Promise((resolve, _reject) => {
      setTimeout(() => {
        resolve()
      }, milliSeconds)
    })
  }

const sendEmails = async (items) => {
    for (let i = 0; i < items.length; i++) {
        const currentItem = items[i];
        await SendMail(currentItem);
        await sleep(5000)
    }
}

正如您看到的sendEmails是一个异步函数,那么您可以通过以下方式调用它:

await sendEmails(items)

匿名用户

不确定你想要实现什么,但你可能需要这个-

async function timeout(interval) {
    return new Promise(resolve => {
    setTimeout(resolve, interval);
  });
}

new Promise( async (resolve, reject) => {

  Promise.all(items.map( async (item, i)=>{ 
    await timeout(5000 * i).then(() => {
        return await SendMail(item);
    });
  }))
  .then(mailsRes => {
    resolve(mailsRes)
  }) 
          
});

问题是setTimeout会立即解决,并且在下一次回调中会得到一个超时取消器。