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