Home:ALL Converter>How to asynchronously iterate over array with javascript & promises

How to asynchronously iterate over array with javascript & promises

Ask Time:2016-11-03T20:53:29         Author:Trung Tran

Json Formatter

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:

  1. check if product's product code is already in the database
  2. if it is in the database, look @ the next product
  3. 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!

Author:Trung Tran,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40402035/how-to-asynchronously-iterate-over-array-with-javascript-promises
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
yy