Home > Net >  Getting array of undefined, promise
Getting array of undefined, promise

Time:12-01

So, from code below im getting array of udefined but to be honest idk why and how to fix it...

const promises = sessionsIds.map((id) =>
            stripe.checkout.sessions
                .listLineItems(id, { limit: 100 })
                .then((err, lineItems) => {
                    return lineItems;
                })
        );

        const usernames = await Promise.all(promises);

I have also tried with async await but the result is still the same.

CodePudding user response:

Assuming that stripe.checkout.sessions.listLineItems(id, { limit: 100 }) is returning a regular, standard promise, then the problem is that you're treating is like a regular asynchronous callback with (err, value) as the functions arguments. That's not how .then() works. The first argument to .then() is a function that will be called with one argument, the resolved value. In fact, you probably don't even need a .then() here.

You can change to this:

const promises = sessionsIds.map((id) =>
    stripe.checkout.sessions.listLineItems(id, { limit: 100 })
);

const usernames = await Promise.all(promises);

Or, simplifying further:

const usernames = await Promise.all(sessionsIds.map((id) =>
    stripe.checkout.sessions.listLineItems(id, { limit: 100 })
));

Note, the .then() handler here is not necessary (assuming stripe.checkout.sessions.listLineItems(id, { limit: 100 }) already returns a promise). If you want to use a .then() handler, it would go like this:

const promises = sessionsIds.map((id) =>
    stripe.checkout.sessions.listLineItems(id, { limit: 100 })
      .then((lineItems) => {
           console.log(lineItems);
           return lineItems;
      });
);

const usernames = await Promise.all(promises);

Where you pass it a function as the first argument and it gets one argument (the resolved value).

  • Related