1

Why is it that when showOrders gets called the orders array is empty? My service is returning 4 objects and I can walk through the item initialization in the .push call but the array returned is always empty.

var showOrders = function(orders){
    $.each(orders, function(i, val){

        alert(val.Order + "::" + val.Href);         

    });
}
var orders = (function(d){
    var _r = [];
    $.getJSON("/_vti_bin/listdata.svc/Orders", function (data) {
        for(var i = 0; i < data.d.results.length; i++)
        {
            var o = data.d.results[i];

            _r.push({
                    Id: o.Id,
                    Order: o.Order, 
                    PurchaseDate: o.PurchaseDate, 
                    CustomerPO: o.CustomerPO, 
                    PurchasedBy: o.PurchasedBy, 
                    SubTotal: o.SubTotal, 
                    Status: o.Status,
                    Href: o.Path + "/DispForm.aspx?ID=" + o.Id
            });
        }
        return _r;
    });
    d(_r);
})(showOrders);  
3
  • 2
    I think there will be async call so till you get data.. your each function start executing Commented Feb 1, 2013 at 14:04
  • 1
    This type of question is asked about a 100 times a day. Asynchronous calls can not return back values! It is like making a call to order pizza. You can not eat it until it is delivered. Commented Feb 1, 2013 at 14:18
  • I think you can see from the use of the delegate I am passing in that it was my intent to call the delegate after the data was retrieved. I just had the call in the wrong line. Commented Feb 1, 2013 at 18:56

1 Answer 1

3

$.getJSON is excecuting an async call. you need to excecute the d-callback inside the callback of the getJSON-call (after your loop):

var orders = (function(d){
  var _r = [];
  $.getJSON("/_vti_bin/listdata.svc/Orders", function (data) {
      for(var i = 0; i < data.d.results.length; i++)
      {
          var o = data.d.results[i];

          _r.push({
                Id: o.Id,
                Order: o.Order, 
                PurchaseDate: o.PurchaseDate, 
                CustomerPO: o.CustomerPO, 
                PurchasedBy: o.PurchasedBy, 
                SubTotal: o.SubTotal, 
                Status: o.Status,
                Href: o.Path + "/DispForm.aspx?ID=" + o.Id
        });
      }
      d(_r);

  });

})(showOrders);  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.