当在 AWS Lambda 中使用 NodeJS 并且使用异步 / 等待操作时,有一个可能出现的问题就是嵌套的 Await / Async 不会返回。这是因为在 AWS Lambda 的上下文中,异步操作可能会造成返回值的丢失。
一种解决方法是使用 Promise.all(),将所有异步操作的返回值包装为一个 Promise 对象,然后通过 await 等待 Promise.all() 的返回值。下面是代码示例:
async function myFunction() { const result1 = await asyncOperation1(); const result2 = await asyncOperation2(); const result3 = await asyncOperation3();
const results = await Promise.all([result1, result2, result3]); return results; }
另外,也可以使用 try/catch 来处理嵌套的 Await / Async 过程中出现的异常。
async function myFunction() { try { const result1 = await asyncOperation1(); const result2 = await asyncOperation2(); const result3 = await asyncOperation3();
return [result1, result2, result3];
} catch (err) { console.error(err); } }