javascript中for循环中的匿名回调函数

时间:2022-12-08 19:57:28

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:

我正在尝试在async.waterfall中创建一个函数,如果mongodb中有任何带有此id的条目(使用Mongoose),则会检查数组中的每个id。如果id已经存在,那么它将从数组中删除。我写了以下函数:

    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.

然而,这会发出警告,因为在for循环中构造了一个新函数。

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

如果我在for循环之外创建函数,如下所示,则会出现错误:ReferenceError:err未定义。

    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?

这样做的正确方法是什么?

1 个解决方案

#1


3  

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));

#1


3  

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));