admin管理员组

文章数量:1327661

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('plete 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.

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('plete 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.

Share Improve this question edited Aug 26, 2017 at 4:35 QWERTY asked Aug 16, 2017 at 1:46 QWERTYQWERTY 2,3259 gold badges52 silver badges87 bronze badges 13
  • promise is undefined – guest271314 Commented Aug 16, 2017 at 1:50
  • yup, i didn't find promise either. – tibetty Commented Aug 16, 2017 at 1:53
  • note, let promiseKey = ... will resolve, almost immediately to undefined because populateData doesn't return anything – Jaromanda X Commented Aug 16, 2017 at 1:55
  • @JaromandaX "I'm surprised at the error you are getting though" See original post. promise was not defined. After the edit datasetarr is still undefined at .then() – guest271314 Commented Aug 16, 2017 at 1:58
  • no, I see why datasetarr is undefined, because populateData returns undefined - and populateData would fail the second time around, because datasetarr.push will fail as dataserarr argument would be undefined second time around – Jaromanda X Commented Aug 16, 2017 at 1:59
 |  Show 8 more ments

2 Answers 2

Reset to default 3

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('plete 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};
        }); 
    }))); 
}

While it's possible to work with a global datasetarray variable to which you push from anywhere, I would remend 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('plete 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;
}

本文标签: