Reputation: 11781
I have an array of "products". I want to save these products to the database if the database is empty, and when all of the db operations finish i want to display a message.
I could not manage to do it using bluebird promises (using .all or .map). I was able to create an item by just returning Product.create(products[0]). I can't wrap my head around it, I am new to promises.
This is the bootstrap file of my sails.js project but this question is about how to use bluebird promises. How can I manage to wait for multiple async tasks (create 3 products) to finish and then continue?
products = [
{
barcode: 'ABC',
description: 'seed1',
price: 1
},
{
barcode: 'DEF',
description: 'seed2',
price: 2
},
{
barcode: 'GHI',
description: 'seed3',
price: 3
}
];
Product.count()
.then(function(numProducts) {
if (numProducts > 0) {
// if database is not empty, do nothing
console.log('Number of product records in db: ', numProducts);
} else {
// if database is empty, create seed data
console.log('There are no product records in db.');
// ???
return Promise.map(function(product){
return Product.create(product);
});
}
})
.then(function(input) {
// q2) Also here how can decide to show proper message
//console.log("No seed products created (no need, db already populated).");
// vs
console.log("Seed products created.");
})
.catch(function(err) {
console.log("ERROR: Failed to create seed data.");
});
Upvotes: 0
Views: 271
Reputation: 11781
Figured it out...
products = [
{
barcode: 'ABC',
description: 'seed1',
price: 1
},
{
barcode: 'DEF',
description: 'seed2',
price: 2
},
{
barcode: 'GHI',
description: 'seed3',
price: 3
}
];
Product.count()
.then(function(numProducts) {
//if (numProducts > 0) {
if(false) {
// if database is not empty, do nothing
console.log('Number of product records in db: ', numProducts);
return [];
} else {
// if database is empty, create seed data
console.log('There are no product records in db.');
return products;
}
})
.map(function(product){
console.log("Product created: ", product);
return Product.create(product);
})
.then(function(input) {
console.log("Seed production complete.");
})
.catch(function(err) {
console.log("ERROR: Failed to create seed data.");
});
Upvotes: 1