📅  最后修改于: 2023-12-03 15:18:42.611000             🧑  作者: Mango
在 JavaScript 中,我们经常需要同时发送多个电子邮件。使用 Promise.all 方法可以轻松地发送一组异步电子邮件,并在所有邮件发送完成后获得结果。
Promise.all 方法接收一个包含多个 Promise 的数组,并返回一个新的 Promise。这个新的 Promise 在所有传入的 Promise 都解析成功后才会解析,并且解析值是一个包含每个 Promise 解析值的数组。
Promise.all(promises)
.then(function(results) {
// 所有 Promise 都成功解析
console.log(results);
})
.catch(function(error) {
// 至少一个 Promise 解析失败
console.error(error);
});
假设我们有一个 sendEmail
函数用于发送电子邮件,并返回一个异步 Promise。
function sendEmail(recipient, message) {
return new Promise(function(resolve, reject) {
// 发送电子邮件的逻辑
// ...
if (emailSentSuccessfully) {
resolve("Email sent successfully to " + recipient);
} else {
reject("Failed to send email to " + recipient);
}
});
}
现在我们可以使用 Promise.all 发送多个电子邮件。
const recipients = ["user1@example.com", "user2@example.com", "user3@example.com"];
const message = "Hello! This is an important message.";
const promises = recipients.map(function(recipient) {
return sendEmail(recipient, message);
});
Promise.all(promises)
.then(function(results) {
console.log(results);
// ["Email sent successfully to user1@example.com",
// "Email sent successfully to user2@example.com",
// "Email sent successfully to user3@example.com"]
})
.catch(function(error) {
console.error(error);
});
使用 Promise.all 方法可以方便地发送一组异步电子邮件,并在所有邮件发送完成后获得结果。这可以显著提高邮件发送的效率和性能。
注意,如果任何一个 Promise 失败,Promise.all 将立即返回一个拒绝的 Promise,并且后续的 Promise 不会被执行。因此,确保在发送失败时正确处理错误。
以上就是使用 Promise.all 发送电子邮件的介绍和示例代码。希望本文能帮助您更好地理解如何利用 Promise.all 处理多个异步任务。