dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 376 forks source link

Passing arguments to callbacks #608

Closed Josema closed 9 years ago

Josema commented 9 years ago

I am not able to pass the variable i.

for (var i=0; i<list.length; ++i) {

    Player.find({name: list[i].name}, function(err, item){
        if (item.name == list[i].name)
            // more code
    });

}

In the example above the value of i its the same of list.length and i am not able to access to the correct itme of list. What is the best way to solve this problem?

Josema commented 9 years ago

This solution solve the problem. But i would like to know if exists a solution using the architecture of orm2.


for (var i = 0; i < list.length; ++i) {

    Player.find({ name: list[i].name}, (function(i) {
        return function(err, item) {
            if (item.name == list[i].name)
            // more code
        }
    })(i));

}
dresende commented 9 years ago

Another more common form:

for (var i = 0; i < list.length; i++) {
    (function (list_item) {
        Player.find({ name: list_item.name }, function (err, item) {
            if (item.name == list_item.name) {
                // ....
            }
        });
    })(list[i]);
}

Please provide a more real example because the if condition makes no sense in this example and chaining might be a solution depending on the real example.

Josema commented 9 years ago

I just want to check if exists the item, if exists update it, if not create it.

dresende commented 9 years ago

Then just check err (there's a not found error).

for (var i = 0; i < list.length; i++) {
    Player.find({ name: list[i].name }, function (err, item) {
        if (err) {
            // create it..
        }
    });
}
Josema commented 9 years ago

To create it, i have to be able to access to the correct item of list. Thats why i have to pass the i parameter or the list item.

Anyway. Are u sure that err is only defined when already exists? Mysql can throw errors for other reasons i guess.

dresende commented 9 years ago

I might be confusing (I think the "not found" error is only for .get). In your case, if name is a unique column (or index..) you can just check if item (which actually should be an Array) is empty or not.

dresende commented 9 years ago

Player.find should always get you an Array, even if the results are one element.

As an alternative:

for (var i = 0; i < list.length; i++) {
    Player.get({ name: list[i].name }, function (err, player) {
        if (err && err.code == orm. ErrorCodes.NOT_FOUND) {
            // create it..
        }
    });
}

In this case you could just check if player is undefined. Here is the code.