javascript - Promise.all 在 AWS lambda 代码中不起作用
问题描述
我已经在本地多次测试过这段代码,但是在 AWS 上部署后,它就停止了工作。我刚刚添加了简单的代码来测试 Promise.all,但该函数根本不等待。我在这里做错了什么?
export const myHandler = async (event, context, callback) => {
console.log(event)
await getParam().then(
(resolvedValue) => {
createBuckets()
},
(error) => {
console.log(get(error, 'code', 'error getting paramstore'))
return { test: error }
}
)
async function createBuckets() {
console.log(`inside createbuckets`)
const timeOut = async (t: number) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Completed in ${t}`)
}, t)
})
}
await timeOut(1000).then((result) => console.log(result))
await Promise.all([timeOut(1000), timeOut(2000)])
.then(() => console.log('all promises passed'))
.catch(() => console.log('Something went wrong'))
}
}
我的 createBuckets 函数也是一个 const 和箭头函数。但由于某种原因,即使在我部署它时也显示为未定义。当我将其更改为函数 createBuckets 时,它开始工作。
解决方案
正如马特在评论中已经提到的那样,您需要return createBuckets()
在.then
回调中才能使其正常工作。
我也认为混合async/await
可能.then/.catch
会有点混乱,所以最好在大多数情况下坚持使用其中一种。
以下是我将如何重写您的代码:
const timeOut = (t: number) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Completed in ${t}`)
}, t)
})
}
async function createBuckets() {
console.log(`inside createbuckets`)
const result = await timeOut(1000);
console.log(result);
await Promise.all([timeOut(1000), timeOut(2000)])
console.log('all promises passed')
// The Promise from timeOut cannot reject, so there's no point in catching it.
// If you need to catch the error when you perform some real work, then you can
// use try/catch.
}
export const myHandler = async (event, context, callback) => {
console.log(event)
try {
const param = await getParam()
await createBuckets()
} catch (error) {
console.log(error)
return { test: error }
}
}
推荐阅读
- kubernetes - Kubernetes 零停机部署不起作用 - 导致 503 服务暂时不可用
- php - Guzzlehttp\Exception\ConnectionException:cURL 错误 28 在 2851 毫秒后解决超时
- angular - 如何从 LocalStorage 中检索值
- java - 重定向到 Spring Boot 中的不同主机(非 www 到 www URL)
- python - DOIT_SEEK_FILE 有什么用
- ios - 推送通知正在接收,但在 PubNub 聊天消息中发送时后台获取未使用 pn_apns 标签调用有效负载
- c# - 如何使用 LINQ 或 C# 其他方式匹配来自两个数据表的数据具有单行
- react-native - 如何用一个反应组件触发两个功能?
- load-balancing - 如何使用 HA 代理服务器作为负载均衡器
- javascript - 是否有必要提交由 blob 包裹的表单?什么是最佳做法?