首页 > 解决方案 > 异步/等待不工作 AWS lambda,等待后跳过所有内容

问题描述

我正在尝试使用 AWS lambda 来测试一些 API 调用axios,但是我遇到了一些麻烦。我遇到的每一篇文章都说,在 Lambda 中处理 promise 的最佳方式是使用async/await而不是.then,所以我进行了转换。当我使用它运行程序node时,它运行良好,但是当我在本地调用 Lambda 时,似乎axios调用之后的所有内容都被跳过了。当我在没有 的情况下在本地调用 Lambda 时await,它之后的调用运行良好,但是我不得不使用.thenLambda 无论如何都不会等待的调用。我已将 Lambda 超时时间增加到900,并且每次都运行sam build过。sam invoke local

function checkServers() {
    console.log("Inside checkServer");
    console.log("Before apis to test");

    // apisToTest has length of 2
    apisToTest.forEach(async (apiToTest) => {
        console.log("Api to test");
        let res = await axios(apiToTest)
        console.log("x"); // This gets skipped
        console.log(res); // This gets skipped
    })
    console.log("After api to test")
}

exports.lambdaHandler = async (event, context) => {
    console.log("Inside lambda handler");
    checkServers();
    console.log("After lambda handler");
};

// Used to test app using node command
checkServers()

这会产生以下输出:

INFO    Inside lambda handler     
INFO    Inside checkServer        
INFO    Before apis to test       
INFO    Api to test
INFO    Api to test
INFO    After api to test
INFO    After lambda handler

标签: node.jsamazon-web-servicesaws-lambdaasync-await

解决方案


感谢您的所有回复,不幸的是,这些并不是我用例的理想解决方案,尽管它们对我提出解决方案非常有帮助。

async function checkServers() {
    let emailBody = "";
    let callResult = "";
    let completedCalls = 0;
    let promises = [];
    for (const apiToTest of apisToTest) {
        await axios(apiToTest).then((res) => {
            // Do something
        }).catch((r) => {
            // Handle error
        })
    }
}

exports.lambdaHandler = async (event, context) => {
    context.callbackWaitsForEmptyEventLoop = true;
    await checkServers();
};

总而言之,我将调用替换为forEach调用for...of,将 更改checkServersasync,并结合awaitand.then().catch处理Promise结果。我不知道两者都可以同时使用。希望这可以帮助任何遇到与我类似的问题的人。


推荐阅读