0

I have this method loadAllCustomObjects that calls the async function loadCustomObject (which does a fetch) multiple times and reduces the results:

export default class CustomObjectLoader {

    static async loadAllCustomObjects(elements) {
        const customObjectTypes = getCustomObjectTypes(elements);
        console.log('loadAllCustomObjects', customObjectTypes);
        const customObjectsData = await customObjectTypes.reduce(async (allData, elementType) => {
            allData[elementType] = await loadCustomObject(elementType)
            return allData;
        }, {});
        console.log('customObjectsData', _.keys(customObjectsData));
        return customObjectsData;
    }

}

However, reduce returns too early, and this is the log statements:

loadAllCustomObjects [ 'slider', 'twitter-share-button' ]
customObjectsData [ 'slider' ]

How can I make it complete all the objects in customObjectTypes?

Tom Söderlund
  • 4,743
  • 4
  • 45
  • 67
  • 2
    I don't think that `reduce()` understands `async` functions. It expects the return value from the callback to be the accumulator value, and it won't do anything special when it sees a Promise. – Pointy Oct 05 '17 at 21:00
  • Possible duplicate of [JavaScript array .reduce with async/await](https://stackoverflow.com/questions/41243468/javascript-array-reduce-with-async-await) – BCartolo Oct 05 '17 at 21:02
  • I solved it by using `reduce` in [`promise-async`](https://github.com/Kikobeats/promise-async) (=a Promise wrapper on `async`) instead. – Tom Söderlund Oct 06 '17 at 07:04

0 Answers0