I read the stream of data from the CSV file in a row line by line and call findOne MongoDB for each line, how can I wait for all the mango calls from each line to complete before I run the next function?
I saw Promises can do this? But I find Promises extremely difficult to understand. And not one of the examples that I have found seems to cover what I'm trying to do.: /
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 be called at the end of the data stream, and not after Monogo calls.
If I can use promises, can someone explain how?
source share