0

For some reason when the function below is called, it returns "UNDEFINED".

We checked and the accumulator returns what it should (We tried printing to log what it holds, and it is a list of items) but the "reduce" function returns an empty array.

(We tried saving its value into an array and printing it to log, it was empty "{}").

Here is the code:

createItemsList = (order: Order) => {
    return order.items.reduce((accumulator: { [key: string]: Item }, item) => {
        let promiseItem = api.getItem(item.id);
        promiseItem.then(currItem => accumulator[item.id] = currItem);
        return accumulator;
    }, {});
};

Any ideas?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    "UNDEFINED" ≠ "empty array" ≠ "{}". Can you please be more accurate and provide a [mcve]? – str Sep 26 '20 at 13:47
  • 1
    The returned value is going to be an empty object, since the synchronously executed code just keeps returning the same accumulator object without change. The property assignments happen later, asynchronously. See the referenced question for all about asynchronous programming. – trincot Sep 26 '20 at 13:50

0 Answers0