node.js - 异步/等待不工作 AWS lambda,等待后跳过所有内容
问题描述
我正在尝试使用 AWS lambda 来测试一些 API 调用axios
,但是我遇到了一些麻烦。我遇到的每一篇文章都说,在 Lambda 中处理 promise 的最佳方式是使用async/await
而不是.then
,所以我进行了转换。当我使用它运行程序node
时,它运行良好,但是当我在本地调用 Lambda 时,似乎axios
调用之后的所有内容都被跳过了。当我在没有 的情况下在本地调用 Lambda 时await
,它之后的调用运行良好,但是我不得不使用.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
解决方案
感谢您的所有回复,不幸的是,这些并不是我用例的理想解决方案,尽管它们对我提出解决方案非常有帮助。
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
,将 更改checkServers
为async
,并结合await
and.then()
来.catch
处理Promise
结果。我不知道两者都可以同时使用。希望这可以帮助任何遇到与我类似的问题的人。
推荐阅读
- jersey - 是否可以全局设置 JSON-B (Yasson) 中的默认日期格式,而不是在每个属性上添加注释?
- javascript - Mongodb不保存数据
- python - 使用 scikit 在 python 上将图像转换为灰度
- batch-file - 使用批处理,为什么 %string% GTR/GEQ 数等于 true?
- c++ - 如何使用 regex_replace 将字符串中的子字符串替换为另一个子字符串,同时保持整个文本的完整性?
- javascript - 在 Safari 中的任何视图下查看时无法查看网站的下部
- google-drive-api - 谷歌云共享表问题,找不到iam.gserviceaccount.com
- php - 在 Guzzle 中使用 ssl 验证模拟 curl 请求
- function - 如何在 Scilab 中使用 Newton Rapshon 方法找到函数的所有根?
- arrays - 将列解析为单独的数组