Uncaught (in promise) TypeError: Cannot read property 'length' of undefined at promiseKey.then

后端 未结 2 1535
无人及你
无人及你 2021-01-25 23:17

I am trying to return an array of pushed data from promise, then loop multiple times to populate all data. For instance, I got a list of brands and a function to take in brand p

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-26 00:05

    While it's possible to work with a global datasetarray variable to which you push from anywhere, I would recommend against it. Instead, write a method getData that returns (a promise for) an array, and after calling that multiple times (once for every brand) you concatenate them together.

    const brandlist = ['Bh', 'Ruffles'];
    const promiseKey = Promise.all(brandlist.map(getData)).then(arrays => [].concat(...arrays));
    promiseKey.then(arr => {
        console.log('complete promise');
        for (const item of arr)
            console.log(item.date + ' ' + item.total);
    });
    
    function getData(brand) { // no array parameter!
        console.log('go in');
        const query = …; // query by brand parameter
        return query.once('value').then(data => {
            const promises = toArray(data).map(snapshot => {
            const query = …; // get receipt item details by receipt ID
            return query.once('value').then(data => { 
                …
                return {date: date, total: itemTotal}; // don't push, just return the result
            });
            return Promise.all(promises); // resolves with an array of results
        }); // resolves with that same result array
    }
    function toArray(forEachable) {
        const arr = [];
        forEachable.forEach(x => { arr.push(x); });
        return arr;
    }
    

提交回复
热议问题