综合技术

Variable suddenly becomes undefined in the callback to an Angular $resource function

微信扫一扫,分享到朋友圈

Variable suddenly becomes undefined in the callback to an Angular $resource function
0

I’m building a function in Node that queries my mongoDB
database and returns some results into an object. I’m having trouble getting the object set up correctly though. Here’s my code:

Function to call the MongoDB lookup

$scope.listItems = $resource('http://10.1.1.21\:3000/api/uniques/:query');

  var itemsToList = [
    'designer',
    'store',
    'category'
  ]

  $scope.uniqueLists = {};

  for(var i = 0; i<itemsToList.length; i++){
    $scope.uniqueLists[itemsToList[i]] = [];  
    $scope.listItems.get({query:itemsToList[i]}, function(data){ 
        console.log(itemsToList); // Returns ["designer", "store", "Category"] x3
        console.log(itemsToList[i]); // Returns undefined, undefined, undefined
        console.log('i = ' + i); // Returns 3, 3, 3 (which is really odd, ideas?)

         $scope.uniqueLists[i] = data.query;

    });
  }

Issues with this code are in the comments above. Bizarrely, i == 3
for all 3 loops, when it should equal 0
, 1
, then finish at 2
.

My question is

Can anybody shed light on what’s going on here? It may have something to do with Node’s asynchronous behaviour, but I’m really at a loss here.

Additional Info

My ExpressJS
call that $scope.listItems
is accessing is here, as you can see express
makes data available through res
(ponse) and as far as I know, I can’t pass in i
or itemsToList
here:

exports.uniqueEntries = function(req, res){
    var query = req.params.query;
    console.log(query);
    db.products.distinct(query, function(err, results){
        if (err) {
            console.log("Lookup Error: " + err);
        } else{
            res.json({
                query:results  
            });
        }       
    });
}

Perhaps the issue is that by the time the expressJS
lookup is finished, the three for
loops have finished and i == 2
. I have no idea why the console would log it as i ==3
though, nor do I have any idea of how to block the loop to ensure the lookup finished before continuing on with the next for
loop.

Problem courtesy of: Jascination

Solution


$resource
methods

, including get()
, are asynchronous. So, their callbacks will be called later
. And, in this case, later
is after the for
loop has run to completion.

For any statements inside the callback, i
will have already been incremented to 3
, which is why it’s no longer 0
, 1
, or 2
for:

console.log('i = ' + i);

You can keep each value of i
as it’s incremented by creating a closure
for it around the callback function
:

function createCallback(itemsToList, i) {
  return function (data) {
      console.log(itemsToList); // Returns ["designer", "store", "Category"] x3
      console.log(itemsToList[i]); // Returns undefined, undefined, undefined
      console.log('i = ' + i); // Returns 3, 3, 3 (which is really odd, ideas?)

       $scope.uniqueLists[i] = data.query;
  };
}

for(var i = 0; i<itemsToList.length; i++){
  $scope.uniqueLists[itemsToList[i]] = [];  
  $scope.listItems.get({query:itemsToList[i]}, createCallback(itemsToList, i));
}

Another option, assuming itemsToList
is an Array
, can be to use
.forEach()

in-place of the for
loop as the iterator will be the closure:

itemsToList.forEach(function (item, i) {
  $scope.uniqueLists[item] = [];
  $scope.listItems.get({query:item}, function(data){ 
    console.log(itemsToList);
    console.log(itemsToList[i]);
    console.log('i = ' + i);

    $scope.uniqueLists[i] = data.query;
  });
});

Solution courtesy of: Jonathan Lonowski

阅读原文...


微信扫一扫,分享到朋友圈

Variable suddenly becomes undefined in the callback to an Angular $resource function
0

Node.js Recipes

Read the email Elon Musk sent to Tesla employees calling for 'hardcore' control of expenses

上一篇

NASA和众多民间航太公司合作 开发Artemis计划当中的月球着陆器

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

Variable suddenly becomes undefined in the callback to an Angular $resource function

长按储存图像,分享给朋友