简体   繁体   中英

Loopback Callback inside For-Loop

In a for-loop I call a loopback function (model.find()) and use the callback method. In this method I need the i variable of the for-loop to specify a variable but it is not accessible from closure. I already tried writing (i) or call(this,i) behind the callback function but it didn't work.

for (var i = 0; i < $scope.objects.length; i++) {
                    Priority.find({
                        filter: {
                            where: {priority: $scope.selectedPriority[i].priority}
                        }
                    }, function (prios) {
                            Priority.create({"priority": $scope.selectedPriority[i].priority //i is not accessible
                            }, function (priority) {
                                $scope.selectedPriority[i].priority = undefined; //i is not accessible
                            }, function (error) {
                                console.log(error);
                            });
                        }
                    });

        }

Actually "i" should be defined but you'll always find it at its highest value (= $scope.objects.length - 1), the reason is that since Priority.find is asynchronous, once it returns an answer, the for loop has already done iterating.

To solve it, you could put body of the loop inside a function:

 function find(i) {
    Priority.find({
                            filter: {
                                where: {priority: $scope.selectedPriority[i].priority}
                            }
                       }, function (prios) {
                               Priority.create({"priority": $scope.selectedPriority[i].priority //i is not accessible
                               }, function (priority) {
                                  $scope.selectedPriority[i].priority = undefined; //i is not accessible
                              }, function (error) {
                                 console.log(error);
                              });
                         }
                      });
}

So then, the for loop becomes:

for (var i = 0; i < $scope.objects.length; i++) {
    find(i);
}

essentially, you're "capturing" the value of "i" and send it as a function argument, as long as you're in the context of a specific function call, i stays fixed.

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