Asynchronous XHR calls with done() function


  • Hello,

    This might be a simple one, but I am trying to figure out the best way to deal with asynchronous functions dealing with promises. Here's a recreation of my code design:

    var list = new WinJS.Binding.List(); generateItems().forEach(function (item) { list.push(item); }); . . . . function generateItems() {

    Retrieve a list of feed sources from Azure Mobile Services. Also involves asynchronous call with a done function

    */ Initialize some XHR calls to multiple sources (blogs) and put all the promises in an array */ WinJS.Promise.join(dataPromises).done(function () { groupData.forEach(function (feed) { feed.dataPromise.then(function (articlesResponse) { /* Process the XML feed here *? }); //return groupData; }); return groupData; }

    Now, when this executes, my Binding List does not contain any data! I think the generateItems() function returns the groupData variable before even it has been populated. So I tried putting the return statement inside the done function (As commented in the code). But this way, I get a compile error "Unable to get property 'forEach' of undefined or null reference". What is the best possible way to do this without changing the code design too much?

    Thanks in advance for your time!


    Monday, October 15, 2012 6:25 AM


  • You could call the then function in your WinJS.Promise.join(dataPromises).then(...) and return a promise instead of returning the groupData. On the returned promise, you could populate the list in the then function of the returned promise.
    • Marked as answer by Song Tian Friday, November 9, 2012 6:27 AM
    Thursday, November 8, 2012 7:37 PM