首页 > 解决方案 > 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 时,它开始工作。

日志

标签: javascriptnode.jstypescriptaws-lambdapromise

解决方案


正如马特在评论中已经提到的那样,您需要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 }
  }
}

推荐阅读