Skip to content Skip to sidebar Skip to footer

How Do I Loop Through An Array Item Of Json And Make Async API Requests With Certain Json Objects

I apologize if my question seems kind of newbie, I'm very new to async programming and I'm still trying to figure everything out. I'm also trying to figure out how to ask good ques

Solution 1:

Your main issue is that .forEach(async is very rarely, if at all, going to work like you expect

However, the other issue is

const price = await stripe.prices.retrieve(item.price_id)
.then(function(message) {
    console.log(message.unit_amount);
    //log the unit_amount value from price object
  },
  function(error) {
    console.log("Reject:", error);
  }
);

This will result in price being undefined - since the .then doesn't return anything

It's always (usually) not a good idea to mix .then/.catch with async/await

So - fixing those two issues - your code becomes

const stripe = require('stripe')('sk_test_51Hemg7ETi3TpMq6bUmiw1HoxERPmReLOT3YLthf11MEVh4xCmnsmxtFHZRlWpimoSnwHjmUOKNkOFsbr9lEEIybe00SQF71RtF');
//This is a test secret key for a dummy stripe account, don't worry I'm not sharing anything sensitive
const express = require('express');
const app = express();
app.use(express.static('.'));
const YOUR_DOMAIN = 'http://localhost:4242';

app.post('/create-session', async(req, res) => {
    //Body of the POST request
    const cartContents = [{
            product_id: 'prod_IHb8dX3ESy2kwk',
            quantity: '2',
            price_id: 'price_1Hh1wcETi3TpMq6bSjVCf3EI'
        }, {
            product_id: 'prod_IFIIyTO0fHCfGx',
            quantity: '2',
            price_id: 'price_1HeniJETi3TpMq6bPDWb3lrp'
        }
    ];

    //Array to push parsed data onto for line_items object in stripe session
    const lineItems = [];
    try {
        for (let item of cartContents) {
            //Retrieve price object from stripe API:
            const price = await stripe.prices.retrieve(item.price_id);
            console.log(price.unit_amount);
            //log the unit_amount value from price object
            //retrieve product object from stripe API
            const product = await stripe.products.retrieve(item.product_id);
            console.log(product.name);
            // retrieve "name" and "images" from returned product object and assign to variable
            const productName = product.name;
            const productImage = product.images;
            //retrieve "unit_amount" from returned price object and assign to variable
            const productPrice = price.unit_amount;
            //retrieve item quantity from cartContents object and assign to variable
            const productQuantity = item.quantity;
            //Add variables to item and push to lineItems array
            lineItems.push({
                price_data: {
                    currency: 'usd',
                    product_data: {
                        name: productName,
                        images: [productImage],
                    },
                    unit_amount: productPrice,
                },
                quantity: productQuantity,
            });
        }
        const session = await stripe.checkout.sessions.create({
            payment_method_types: ['card'],
            line_items: lineItems,
            mode: 'payment',
            success_url: `http://localhost:5001/success.html`,
            cancel_url: `http://localhost:5001/cancel.html`,
        });
        res.json({id: session.id});
    } catch(e) {
        // handle error here
    }
});

Post a Comment for "How Do I Loop Through An Array Item Of Json And Make Async API Requests With Certain Json Objects"