我正在尝试使用 AWS lambda 来使用 axios
测试一些 API 调用,但是我遇到了一些麻烦。我遇到的每个帖子都说在 Lambda 中处理 Promise 的最佳方法是使用 async/await
而不是 .then
,所以我做了转换。当我使用 node
运行程序时它工作得很好,但是当我在本地调用 Lambda 时,似乎是在 axios
之后的所有内容。正在跳过调用。当我在没有 await
的情况下在本地调用 Lambda 时,之后的调用运行良好,但随后我不得不使用 .then
无论如何,Lambda 不会等待。我已将 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
最佳答案
你有两个选择:
callbackWaitsForEmptyEventLoop
为 true - 然后 AWS 将等到 eventloop 为空 checkServers
上等待您的 promise .考虑使用 await Promise.all([...])
等待你所有的 promise 完成。 注意:如果您将再次运行 lambda,来自前一次调用的事件可能会“泄漏”到下一次调用。
你可以在这里了解它:https://lumigo.io/blog/node-js-lambda-execution-leaks-a-practical-guide/
披露:我在发布这篇博文的公司工作
关于node.js - 异步/等待不适用于 AWS lambda,等待后跳过所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64630043/