【问题标题】:My async/await function is not waiting in AWS Lambda. What am I missing?我的 async/await 函数没有在 AWS Lambda 中等待。我错过了什么?
【发布时间】:2020-03-30 21:18:55
【问题描述】:

我在 AWS Lambda 中有一个函数可以在 Stripe 中检索用户详细信息。但是函数之后的代码首先执行。我错过了什么?

在我的例子中,该函数调用一个返回客户对象的 Stripe 函数。

我认为 Stripe 函数的细节与这个特定问题无关——问题是我的 async/await 的结构:

module.exports.getUserName = async (event, context)=>{

  [code to get customerId from stripe]

  var customerName

  await stripe.customers.retrieve(customerId, function(err, customer){
      if (err){}
      else{
       customerName = customer.name
     }
  })

  console.log('This should run after stripe.customers.retrieve')

}

现在 console.log 语句首先运行。我还尝试将 Stripe 函数包装在一个单独的异步函数中,并尝试添加 try/catch。但它还没有工作。

如何确定控制台日志语句在 stripe.customers.retrieve 之后运行?

【问题讨论】:

    标签: node.js aws-lambda


    【解决方案1】:

    编辑: 我检查了 source 的 npm stripe 包。所有的函数都会返回 Promises,但是如果你另外提供一个回调,它们会被安排在下一个事件循环中被调用(在你的 console.log 运行之后立即)。

    如果您要使用 Promise,您需要做的只是不提供回调。请改用Promise.then()

    await stripe.customers.retrieve(customerId).then(customer => {
       customerName = customer.name
       resolve()
    }).catch(_=>{})
    

    旧答案(仍然有效,但非常多余):

    awaitPromises 一起使用,它不会神奇地将异步代码转换为同步代码。我可以从老式的 function(err, customer){ 回调中看到,您的 stripe.customers.retrieve() 函数确实返回 Promise,因此 await 实际上不会做任何事情。

    您需要将其包装在一个 Promise 中以便与 async/await 一起使用:

    await new Promise((resolve,reject) => { 
       stripe.customers.retrieve(customerId, function(err, customer) {
          if(!err) {
             customerName = customer.name
             resolve()
          }
       })
    })
    

    【讨论】:

    • 谢谢。实际上,对我来说,你的“旧”答案——完整的承诺结构——完全有效。更新更简洁的答案对我来说不太适用。 "then(customer =>{" 中的 "customer" 不提供完整的对象;并且 stripe.customers.retrieve 函数在控制台日志。
    • 差异可能与您的新答案基于条带 npm 包这一事实有关。我的 lambda 函数没有直接上传——不确定这是否会有所不同。无论如何,原始答案有效。再次感谢!
    猜你喜欢
    • 2021-12-11
    • 2019-05-08
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2022-01-27
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多