2 回答

TA贡献1900条经验 获得超5个赞
您正在寻找
module.exports.test = async (event) => {
var p = download1();
var c = download2();
var h = download3();
try {
await Promise.all([p, c, h]);
// ... bunch of logic manipulating the data
var promises = customers.map(async (i) => {
var data = await buildFile();
var response = await sendEmail(data);
console.log('Email sent successfully');
});
await Promise.all(promises);
} catch(e) {
errHandler(e);
}
};
您的test函数没有等待您在forEach循环中创建的promise ,因此lambda在完成所有操作之前就完成了。

TA贡献1817条经验 获得超6个赞
我想稍微扩展一下,并为您提供一些资源以增加或增强您的Promises知识。我将使用下一个代码段,这有点麻烦,因为我在代码段上编写了代码,Google Chrome因此可以随意将其粘贴并使用它:
(function() {
const promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Replicant');
}, 300);
});
const promise2 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Human?');
}, 300);
});
function buildFile(type) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`${type}`);
}, 300);
});
}
function sendMail(customer, answer) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Sent test to: ${customer}, he/she is a ${answer}`);
}, 300);
});
}
let customers = ['Rob Batty', 'Rachel', 'Deckard'];
async function myFunc() {
const [a, b, c] = await Promise.all([promise1, promise1, promise2]);
const answers = [a, b, c];
// const promises = customers.map(async (name, index) => {
// const file = await buildFile(answers[index]);
// const mail = await sendMail(name, file);
// console.log(mail);
// });
const promises = customers.map((name, index) => {
buildFile(answers[index])
.then(file => sendMail(name, file))
.then(sent => console.log(sent))
// If you're going to use Promises this is important! :D
.catch(err => console.log(err))
});
const [m1, m2, m3] = await Promise.all(promises);
console.log(m1, m2, m3);
}
myFunc();
})()
正如答案中指出的那样,问题与的使用有关forEach,为什么呢?好吧,仅因为您是asynchronous在一种synchronous方法上执行代码,所以相处的不是很好:),因此,解决方案是创建一个Arrayof Promises,如a Factory。后map功能Promises是Pending也不Fullfiled或Rejected当你调用它的Promise.all()方法,你等待他们的结果,他们给你的价值观或你的使用情况,生成该文件,然后将电子邮件发送给用户。我希望这可以帮助您更好地了解其Promises工作原理。最后,我将留下两个非常重要的链接,至少对我来说,这在一定程度上帮助了我Promises。干杯,sigfried。
添加回答
举报