Answered by:
why we cannot use for loop to create WinJS.xhr ??

Question
-
For example :
Sample = [{key:"A"},{key:"B"}];
for(var i = 0 ; i < 5 ; i++ ){
urlText = somefun(i);
WinJS.xhr({ url : urlText }).then({
title = ....;
description = .....;
list.push({group:"Sample[i]",title:title,des:description}); // error
list.push({group:"Sample[0]",title:title,des:description}); // OK.});
}
It cause an error with key is null or undefined . If I need to get feed from many url (For ex: 21 urls) . What should I do ?
Thursday, May 24, 2012 8:52 AM
Answers
-
I think if you study the example in Create Your First Metro Style App Using JavaScript, you will see the technique for looping xhr calls and joining the promises. It looks very much like your scenario.
- Proposed as answer by Jeff SandersMicrosoft employee, Moderator Tuesday, May 29, 2012 7:13 PM
- Marked as answer by Dino He Friday, June 1, 2012 7:39 AM
Sunday, May 27, 2012 12:28 AM
All replies
-
You should chain/join promisses.
- Proposed as answer by Jeff SandersMicrosoft employee, Moderator Thursday, May 24, 2012 6:53 PM
Thursday, May 24, 2012 9:39 AM -
If have to get feed from 21 urls , Then I need 21 group of xhr chaining ?Saturday, May 26, 2012 5:32 PM
-
I think if you study the example in Create Your First Metro Style App Using JavaScript, you will see the technique for looping xhr calls and joining the promises. It looks very much like your scenario.
- Proposed as answer by Jeff SandersMicrosoft employee, Moderator Tuesday, May 29, 2012 7:13 PM
- Marked as answer by Dino He Friday, June 1, 2012 7:39 AM
Sunday, May 27, 2012 12:28 AM -
I ran into something like this as well, where chaining didn't allow me to refer to specific indicies in an array. This is how I got around it:
You make the inner part of the for loop a function so that the array index is preserved as a parameter.
ie.
var list= ["a", "b", "c"]; for(var i=0; i < list.length; i++) { sendXHR(someUrl, i); } function sendXHR(targetUrl, index) { WinJS.xhr({url: targetUrl}).then( function() { //do something title = list[index]; } ); }
-Jeff
Tuesday, May 29, 2012 7:56 PM