AWS-Lambda函数不等待

时间:2019-08-05 00:05:27

标签: javascript async-await aws-lambda

我正在使用AWSs API Gateway以及用于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
        }
    });
}

2 个答案:

答案 0 :(得分:4)

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

  • async sendMail不会执行任何操作(除了使sendMail返回一个立即解决为undefined的承诺
  • 您需要更改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));
    });
}
  

根据@ThalesMinussi的评论,如果您不提供回调函数,transporter.sendMail将返回Promise,因此您可以编写:(sendEmail现在是异步的)

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;
    }
}

答案 1 :(得分:0)

您正在另一个函数内部调用异步函数,这很好,但是由于它返回了一个Promise,因此您也必须等待启动。