繁体   English   中英

Async function inside.map 在第一个数组 object 后抛出错误

[英]Async function inside .map throws error after first array object

我正在尝试遍历一个数组以向每个数组 object 收取费用。 function 适用于第一个阵列 object。 我可以看到条纹一侧的电荷。 条带代码块已经过单独测试,可以正常工作。

router.post('/test', async (req, res) =>{
  try {
    const newItem = req.body.results;
    return auctions = newItem
        .map(x =>({
          auction_id: x._id.$oid,
          status: x.status,
          bid: x.bidHistory.bid.$numberInt,
          name: x.bidHistory.name,
          user_id: x.bidHistory.user
        }))
        .map(async (y) =>{
          //Perform charge here
          try {
            //Get stripe_id
            const user = await User.findOne({uid: y.user_id})
              if (!user.stripe_id) throw Error("User doesn't have a stripe id");
             
            const paymentIntent = await stripe.paymentIntents.create({
              amount: y.bid,
              currency: 'usd',
              customer: (user.stripe_id),
              payment_method: (user.stripe_cc),
              off_session: true,
              confirm: true,
            });
    
            res.status(200).json(paymentIntent);
    
          } catch (err) {
            // Error code will be authentication_required if authentication is needed
            console.log('Error code is: ', err.code);        
            const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id);
            console.log('PI retrieved: ', paymentIntentRetrieved.id);
    
            res.status(400).json(paymentIntentRetrieved.id);
          }  
           
        })      
  } catch (err) {        
    res.status(400).json(err);
  }  
})

尝试循环到数组中的第二个 object 时,出现错误:

"Error code is:  undefined
[0] (node:44590) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'payment_intent' of undefined
[0]     at /Users/Alex/Documents/Webdev/mern-nowaitlist/routes/api/stripe.js:151:89"

这很奇怪,因为它适用于第一个阵列 object。 任何线索这里发生了什么? 在发送另一个条带化请求之前我需要等待吗?

编辑 1:我添加了 promise.all。 该循环仅第一次工作。 我注释掉了所有条纹的东西,看看发生了什么。

router.post('/test', async (req, res) =>{
  try {
    const newItem = req.body.results;
    const auctions = newItem
        .map(x =>({
          auction_id: x._id.$oid,
          status: x.status,
          bid: x.bidHistory.bid.$numberInt,
          name: x.bidHistory.name,
          user_id: x.bidHistory.user
        }))
    const results = Promise.all(auctions    
        .map((y) =>{
          //Perform charge here
          
          try {        
            y.bid= y.bid+1;
            res.status(200).json(y.bid)
          } catch (err) {
            res.status(400).json(err);
            console.log(err)
          }  
           
        }) 
        )  
       return results    
  } catch (err) {        
    res.status(400).json(err);
  }  
})

现在尝试运行代码时出现以下错误:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我不确定您期望err.raw是什么,但似乎err.raw.payment_intent未定义,在您的catch块中引发了一个新错误。

尝试删除支付意图检索并记录错误以首先查看失败的原因,然后修复它。

您传递给 Array.map() 的回调返回 Promise,因此您需要等待它由 Promise.all 解决。 或者使用 for 语句循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM