AWS-Lambda函数不等待等待
我正在使用AWSs API Gateway以及用于API的Lambda函数.
I'm using AWSs API Gateway along with a Lambda function for an API.
在我的Lambda函数中,我有以下(简化的)代码,但是我发现未遵守 await sendEmail
,而是一直返回 undefined
In my Lambda function, I have the following (simplified) code however I'm finding that the await sendEmail
isn't being respected, instead, it keeps returning 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
}
});
}
由于您等待sendMail
,因此需要 sendMail
返回 Promise
-您的代码使用回调处理异步,因此
since you await sendMail
, this requires sendMail
to return a Promise
- your code uses callbacks to handle the asynchrony, so
-
async sendMail
不执行任何操作(使makesendMail
返回Promise,IMMEDIATELY将其解析为undefined
- 您需要更改sendMail以返回Promise(并且它不需要
async
,因为它不需要await
- the
async sendMail
doesn't do anything (except makesendMail
return a Promise that IMMEDIATELY resolves toundefined
- you need to change sendMail to return a Promise (and it won't need
async
since it won't needawait
下面的代码应该做到这一点-
the code below should do it -
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));
});
}
根据@ThalesMinussi的评论,如果不提供回调函数,则
transporter.sendMail
将返回Promise,因此可以编写:(sendEmail现在是异步的)
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;
}
}