Uncaught (in promise) TypeError: Cannot read prope

2019-09-20 08:43发布

问题:

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 parameter and return an array of pushed data.

var datasetarr = [];
brandlist = ['Bh', 'Ruffles'];

let promiseKey = new Promise((resolve, reject) => {
    for(var i = 0; i < brandlist.length; i++){
        datasetarr = populateData(brandlist[i], datasetarr);
    }
    resolve(datasetarr);
});

promiseKey.then((arr) => {
    console.log('complete promise');
    for(var i = 0; i < arr.length; i++){
        console.log(arr[i].date + ' ' + arr[i].total);
    }
});

The error message is

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

My data fetching has no problem as I managed to print out the details. This means that the promise is not resolve properly. Is that the correct way to return an array from promise? I not sure which part was wrong.

回答1:

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};
        }); 
    }))); 
}


回答2:

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;
}