简体   繁体   中英

Anonymous callback function in for loop in javascript

I'm trying to make a function inside an async.waterfall that checks each id in an array if there is any entry in a mongodb with this id (using Mongoose). If the id already exists it's to be removed from the array. I wrote the following function:

    function(eventIds, callback) {
        // check for duplicates
        for (var i = 0; i < eventIds.length; i++) {
            var query = Party.find({
                fbEventId: eventIds[i]
            });
            query.exec(function(err, doc) {
                if (err) return console.log(err);
                if (doc) {
                    // remove i from array
                    console.log(doc);
                }
            });
        }
        callback(null, eventIds);
    }

This however gives a warning because a new function is constructed in a for loop.

If i create the function outside the for loop like below it gives an error: ReferenceError: err is not defined.

    function(eventIds, callback) {
        // check for duplicates
        function checkDuplicate(err, doc) {
            if (err) return console.log(err);
            if (doc) {
                    // remove i from array
                console.log(doc);
            }
        }
        for (var i = 0; i < eventIds.length; i++) {
            var query = Party.find({
                fbEventId: eventIds[i]
            });
            query.exec(checkDuplicate(err, doc));
        }
        callback(null, eventIds);
    }

What would be the proper way to do this?

You are calling the function, not assigning a reference to it.

Your code

query.exec(query.exec(checkDuplicate(err, doc));

should be

query.exec(query.exec(checkDuplicate));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM