gpt4 book ai didi

javascript - AWS - Lambda 函数不等待等待

转载 作者:行者123 更新时间:2023-11-29 10:26:41 25 4
gpt4 key购买 nike

我正在使用 AWS API 网关以及用于 API 的 Lambda 函数。

在我的 Lambda 函数中,我有以下(简化的)代码,但是我发现 await sendEmail 没有得到遵守,相反,它一直返回 undefined

exports.handler = async (event) => {
let resultOfE = await sendEmail("old@old.com", "new@new.com")
console.log(resultOfE)
}

async function sendEmail(oldEmail, newEmail) {
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xxx',
pass: 'xxx'
}
});

transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
return false
} else {
console.log('Email sent: ' + info.response);
return true
}
});
}

最佳答案

由于您await sendMail,这需要sendMail 返回一个Promise - 您的代码使用回调来处理异步,所以

  • async sendMail 不执行任何操作(除了使 sendMail 返回一个立即解析为 undefined
  • 的 Promise
  • 您需要更改 sendMail 以返回一个 Promise(它不需要 async 因为它不需要 await

下面的代码应该可以做到 -

var nodemailer = require('nodemailer'); // don't put require inside a function!!

exports.handler = async (event) => {
const resultOfE = await sendEmail("old@old.com", "new@new.com")
console.log(resultOfE)
}

//doesn't need async, since there will be no await
function sendEmail(oldEmail, newEmail) {
return new Promise((resolve, reject) => { // note, reject is redundant since "error" is indicated by a false result, but included for completeness
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xxx',
pass: 'xxx'
}
});
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
resolve(false);
} else {
console.log('Email sent: ' + info.response);
resolve(true);
}
});
// without the debugging console.logs, the above can be just
// transporter.sendMail(mailOptions, error => resolve(!error));
});
}

as per comment by @ThalesMinussi, transporter.sendMail returns a Promise if you do not provide a callback function, so you could write: (sendEmail is now async)

async function sendEmail(oldEmail, newEmail) {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xxx',
pass: 'xxx'
}
});
try {
const info = await transporter.sendMail(mailOptions);
console.log('Email sent: ' + info.response);
return true;
}
} catch (error) {
console.log(error);
return false;
}
}

关于javascript - AWS - Lambda 函数不等待等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57351008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com