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

后端 未结 2 1500
无人及你
无人及你 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-25 23:56

    Firstly, your populateData needs to return a Promise - in this case, it would be the resolved array of promises created in data.forEach

    var brandlist = ['Bh', 'Ruffles'];
    
    let promiseKey = Promise.all(brandlist.map(brand => populateData(brand)))
    .then(results => [].concat(...results)); // flatten the array of arrays
    
    promiseKey.then((arr) => {
        console.log('complete promise');
        for(var i = 0; i < arr.length; i++){
            console.log(arr[i].date + ' ' + arr[i].total);
        }
    });
    
    function populateData(brand, datasetarr) {
        console.log('go in');
        var query;// = // query by brand parameter
        return query.once('value').then(data => {
            var promises = [];
            data.forEach(snapshot => {
                // get each receipt item details
    
                // get receipt details by receipt ID
                var query;// = // query receipts
                promises.push(query.once('value').then(data => { 
                    // removed code
                    // managed to print out here so data fetching is not a problem
                    console.log(brand + ' ' + date + ' ' + itemTotal);
                    return {date: date, total: itemTotal};
                })); 
            }); 
            return Promise.all(promises);
        });
    }
    

    Or, using the snapshotToArray function I gave you in this answer a week ago

    const snapshotToArray = snapshot => {
        const ret = [];
        snapshot.forEach(childSnapshot => {
            ret.push(childSnapshot);
        });
        return ret;
    };
    
    function populateData(brand, datasetarr) {
        console.log('go in');
        var query;// = // query by brand parameter
        return query.once('value').then(data => Promise.all(snapshotToArray(data).map(snapshot => {
            // get each receipt item details
    
            // get receipt details by receipt ID
            var query;// = // query receipts
            return query.once('value').then(data => { 
                // removed code
                // managed to print out here so data fetching is not a problem
                console.log(brand + ' ' + date + ' ' + itemTotal);
                return {date: date, total: itemTotal};
            }); 
        }))); 
    }
    

提交回复
热议问题