【问题标题】:Promise.all won't work in AWS lambda codePromise.all 在 AWS lambda 代码中不起作用
【发布时间】:2021-08-19 06:19:09
【问题描述】:

我已经在本地多次测试过这段代码,但在 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 时,需要返回一个承诺以等待它。在这种情况下,undefined 返回,而 async createBuckets 在事件循环的下一个刻度上运行
  • 另外,使用async/await 比混入.then promise API 更容易。

标签: javascript node.js typescript aws-lambda promise


【解决方案1】:

正如 Matt 在 cmets 中已经提到的,您需要在 .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 }
  }
}

【讨论】:

    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 2020-06-21
    • 2020-12-02
    • 2023-03-19
    • 2023-03-26
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多