[英]Promise.all won't work in AWS lambda code
我已经在本地多次测试过这段代码,但是在 AWS 上部署后,它就停止了工作。 我刚刚添加了简单的代码来测试 Promise.all,但是 function 根本不等待。 我在这里做错了什么?
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 function 也是一个常量和箭头 function。 但由于某种原因,即使在我部署它时也显示为未定义。 当我将其更改为 function createBuckets 时,它开始工作。
正如 Matt 在评论中已经提到的,您需要在.then
回调中return createBuckets()
才能正常工作。
我还认为混合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 }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.