简体   繁体   English

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

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

I am trying to loop through an array to charge a payment to each array object.我正在尝试遍历一个数组以向每个数组 object 收取费用。 The function works for the first array object. function 适用于第一个阵列 object。 I am able to see the charge on the stripe side so.我可以看到条纹一侧的电荷。 The stripe block of code has been tested separately and works without issue.条带代码块已经过单独测试,可以正常工作。

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);
  }  
})

When trying to loop to the second object in the array, I get an error:尝试循环到数组中的第二个 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"

Which is odd because it worked for the first array object.这很奇怪,因为它适用于第一个阵列 object。 Any clue what's going on here?任何线索这里发生了什么? Do I need to wait before sending another request to stripe?在发送另一个条带化请求之前我需要等待吗?

EDIT 1: I added a promise.all.编辑 1:我添加了 promise.all。 The loop worked only for the 1st time again.该循环仅第一次工作。 I commented out all the stripe stuff to see what was going on.我注释掉了所有条纹的东西,看看发生了什么。

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);
  }  
})

I now get the following error when trying to run the code:现在尝试运行代码时出现以下错误:

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

I'm not sure what you expect err.raw to be, but it appears that err.raw.payment_intent is undefined, throwing a new error within your catch block.我不确定您期望err.raw是什么,但似乎err.raw.payment_intent未定义,在您的catch块中引发了一个新错误。

Try removing the payment intent retrieval and just log the error to see what is failing in the first place, then fix that.尝试删除支付意图检索并记录错误以首先查看失败的原因,然后修复它。

The callback you passed to Array.map() returns Promise, so you need to await for it to be resolved by Promise.all.您传递给 Array.map() 的回调返回 Promise,因此您需要等待它由 Promise.all 解决。 Or loop with a for statement.或者使用 for 语句循环。

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

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