can someone help me with asynchronously iterating over an array using javascript & promises? Here is a simplified breakdown of what I am trying to achieve - I have an array of products that I want to insert into a database. Many of the products in the array are duplicates. Therefore, my algorithm is:
- check if product's product code is already in the database
- if it is in the database, look @ the next product
- if it is NOT in the database, insert the product
I am having issues doing this asynchronously. Here is my code so far:
var checkIfProductExists = function(product_code) {
return new Promise(function(resolve, reject) {
db.collection('products').find( {product_code: product_code } ).toArray(function(err, res) {
if(err) {
console.log('--err checking if product exists');
console.log(err);
} else {
resolve(res)
}
});
});
}
var processRecords = function () {
fetchProducts().then(function(products) { //fetch products to insert
async.each(products, function(product) {
checkIfProductExists(product).then(function(result) {
if(result) {
//product exists; move onto the next product
callback();
} else {
//product doesn't exist; insert it
insertProduct(product);
callback();
}
});
}, function(err) {
if(err) {
console.log('--async error--');
}
});
}
}
processRecords();
However, this logic results in EVERY product in my array being inserted, regardless of whether or not a match was found in my checkIfProductExists
method... Can someone help?
Thanks in advance!
Alnitak :
As written, if the db.find(...).toArray() call fails to find a matching entry it'll return an empty array, not a \"false\" value.\n\nYou should check the length of the result from the checkIfProductExists, or alternatively have that function resolve to a boolean instead of a potentially empty array, i.e.\n\nresolve(res && (res.length > 0));\n",
2016-11-03T14:05:18