I'm reading a data stream from a CSV file row by row, and calling a findOne MongoDB call on each row, how can I wait till all the mongo calls from each row are complete before I run the next function?
I've seen Promises can do it? But I find Promises extremely difficult to understand. And none of the examples I've found seem to cover what I'm trying to it. :/
var validProducts = [];
fs.createReadStream(req.file.path)
.pipe(csvStream)
.on('error', function (err) {
console.error(err);
})
// loop through all rows
.on('data', function (data) {
if (data.size === 'a3') {
ProductModel.findOne({ sku: data.sku }, function (err, product) {
if (product !== null) {
product.size = data.size;
product.save();
validProducts.push(product);
}
});
}
});
// on finish make call to other function
socket.emit({ 'status': 'complete' });
otherFunction(validProducts);
on('finish') or on('end') will only call at the end of the data stream, not after the Monogo calls.
If I can use promises, can someone please explain how?