Home > Software design >  A pending promise is returned from stripe.checkout.sessions.listLineItems each time
A pending promise is returned from stripe.checkout.sessions.listLineItems each time

Time:05-22

Here I am trying to get the data from the firebase and then use that id to retrieve items from stripe checkout. But each time I try this I get a pending promise.

const colRef = collection(db, `users/${session.user.email}/orders`);
const q = query(colRef, orderBy("timestamp", "desc"));

const orders = await getDocs(q)
    .then((snapshot) => {
      snapshot.docs.forEach((sdoc) => {
        orders.push({
          id: sdoc.id,
          items: stripe.checkout.sessions
            .listLineItems(sdoc.id, {
              limit: 100,
            })
            .then((res) => {
              return res;
            })
            .catch((err) => console.log(err)),
        });
      });
      return orders;
    })
    .catch((err) => console.log(err));

I have also tried with await but then my whole array is just returned empty

const colRef = collection(db, `users/${session.user.email}/orders`);
  const q = query(colRef, orderBy("timestamp", "desc"));

  orders = await getDocs(q)
    .then((snapshot) => {
      snapshot.docs.forEach(async (sdoc) => {
        orders.push({
          id: sdoc.id,
          items: await stripe.checkout.sessions
            .listLineItems(sdoc.id, {
              limit: 100,
            })
            .then((res) => {
              return res;
            })
            .catch((err) => console.log(err)),
        });
      });
      return orders;
    })
    .catch((err) => console.log(err));

CodePudding user response:

You'll need to combine the collection of promises with Promise.all. It will look like this:

const snapshot = await getDocs(q);
const orders = await Promise.all(snapshot.docs.map(async (sdoc) => {
  const sessions = await stripe.checkout.sessions
            .listLineItems(sdoc.id);
  return {id: sdoc.id, items: sessions};
}));
  • Related