-1

When I console.log() paymentsResults and pendingResults from the code below, I can see the data being logged properly. However, right at the last moment when I am trying to return payments and pending I see the results as Promise { <pending> } in my backend. What is the reason and how can I fix the issue here?

const query = await pool.query(q);

const payments = query.rows.filter(o => getCategory(o) === "payment");
const pending = query.rows.filter(o => getCategory(o) === "pending");
const inactive = query.rows.filter(o => getCategory(o) === "inactive");

const paymentsResults = payments.map(async order => {

    const A = ({
        date: getDate(order),
        item: await getItem(order),
        total: getTotal(order),
        purchaser: getPurchaser(order),
        email: getEmail(order),
        paymentMethod: getPaidUsing(order),
        status: getStatus(order)
    });
    return A;
});



const pendingResults = pending.map(async order => {

    const B = {
        date: getDate(order),
        item: await getItem(order),
        total: getTotal(order),
        purchaser: getPurchaser(order),
        email: getEmail(order),
        status: getStatus(order)
    };

    return B;
});


return {
    payments: paymentsResults,
    pending: pendingResults,
    inactive: inactive
};
};
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
mark smith
  • 21
  • 5
  • 2
    Probably because you can't `await` inside a synchronous Array method (`.map()`, `.forEach()`, `.filter()`, etc). You have to use a `for` loop if you want to await. – Jeremy Thille Nov 01 '21 at 15:21
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Liam Nov 01 '21 at 15:21
  • @JeremyThille Do you know how to write the `.map` above as a `for` loop instead? – mark smith Nov 01 '21 at 15:28
  • 1
    Of course, it's basically the same thing. Have a look at [for...of loop documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) – Jeremy Thille Nov 01 '21 at 15:32

1 Answers1

0
const paymentsResults = await Promise.all(payments.map(async order => {
    const A = {
        date: getDate(order),
        item: await getItem(order),
        total: getTotal(order),
        purchaser: getPurchaser(order),
        email: getEmail(order),
        paymentMethod: getPaidUsing(order),
        status: getStatus(order)
    };

    return A;
}));


const pendingResults = await Promise.all(pending.map(async order => {
    const B = {
        date: getDate(order),
        item: await getItem(order),
        total: getTotal(order),
        purchaser: getPurchaser(order),
        email: getEmail(order),
        status: getStatus(order)
    };

    return B;
}));

  • array of Promise should be resolved by Promise.all before using.
  • async function always returns promise.
Bad Dobby
  • 811
  • 2
  • 8
  • 22