Reputation: 2202
anyone help me how can i manage this code using async and await feature. My requirement is after inserting 100 data then mongo database disconnected.
var faker = require('faker');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopping');
mongoose.Promise = global.Promise;
var Product = require('../models/product');
async function insertDocument(){
for(var i=0;i<=100;i++){
try{
var product = new Product({
imagePath:faker.image.image(),
title:faker.commerce.productName(),
description:faker.lorem.paragraph(),
price:faker.commerce.price()
});
product.save();
}catch (err) {
console.log(err);
}
}
}
insertDocument().then(function () {
// mongoose.disconnect();
});
Upvotes: 1
Views: 360
Reputation: 43817
product.save()
returns a promise. If you want to insert the 100 documents serially (one after the other) use await
. If you want to insert the 100 documents in parallel you don't need async
and should use Promise.all
async function insertDocument(){
for(var i=0;i<=100;i++){
try{
var product = new Product({
imagePath:faker.image.image(),
title:faker.commerce.productName(),
description:faker.lorem.paragraph(),
price:faker.commerce.price()
});
await product.save();
}catch (err) {
console.log(err);
}
}
}
function insertDocument(){
let promises = [];
for(var i=0;i<=100;i++){
var product = new Product({
imagePath:faker.image.image(),
title:faker.commerce.productName(),
description:faker.lorem.paragraph(),
price:faker.commerce.price()
});
promises.push(product.save());
}
return Promise.all(promises);
}
Upvotes: 3