Arfons
Arfons

Reputation: 96

Using Promise.all() when iterating over a .JSON?

I have a .JSON with several different types of data structures which I iterate over with a group of for loops, each for loop has an async function running on it - namely, an insert on a SQLite database - but I want to wait until all of the inserts from all of the for loops have finished. This is one such loop:

for (let i = 0; i < data.json().products.length; i++) {
    this.product.addItem(data.json().products[i]);
}

And this is the addItem function:

addItem(product){        
    this.productsSQL.query('INSERT INTO ...').then((data) => {
    ...
    }, (error) => {
    ...
    });
}

I would imagine I have to change addItem to be:

addItem(product){        
    return this.productsSQL.query('INSERT INTO ...').then((data) => {
        return true;
    }, (error) => {
        return false;
    });
}

And then each loop I need to use a promise.all() but then I also need a promise.all() that has all of the loops together?

Upvotes: 2

Views: 797

Answers (1)

Hoyen
Hoyen

Reputation: 2519

Basically create a array of promises and update your code to the following should work:

var promises = [];
for (let i = 0; i < data.json().products.length; i++) {
    promises.push(this.product.addItem(data.json().products[i]));
}


Promise.all(promises).then((data) => {
        return true;
    }, (error) => {
        return false;
    });

Have addItem return a promise:

addItem(product){        
    return this.productsSQL.query('INSERT INTO ...');
}

Upvotes: 1

Related Questions