0

I am trying to resolve this issue which is related to http requests.

I need to fire multiple http request inside a for loop. The for loop provides the url for the request. I also need to push project id to an array based from the loop variable.

var array = [];

for(var i = 0; i < project.length; i++) {
    var url = project[i].url

    getProjectDetail(url)
        .then(function(data) {
            console.log(i)   
            //this only outputs project.length which is 10

            array.push ({id:project[i].id, detail:data.detail}) 
            // error here Cannot read property 'id' of undefined
        }
}

It seem like the request takes time and variable i is always the max length. I am not sure how to resolve this issue. Any thoughts?

Thanks so much!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

0

Since the call is asynchronous, by the time the call is made i has been looped through and ends up being the last value. Take the function out of the loop and pass it the required parameters:

var array = [];

var fntocall = function(i, url) {
    getProjectDetail(url)
        .then(function(data) {
            console.log(i)   
            //this only outputs project.length which is 10

            array.push ({id:project[i].id, detail:data.detail}) 
            // error here Cannot read property 'id' of undefined
        }
}

for(var i = 0; i < project.length; i++) {
    fntocall(i, project[i].url);
}
Jonathan Gray
  • 2,509
  • 15
  • 20
  • It seems as though that isn't the only issue with this code. Unfortunately I have no experience using promises. Maybe somebody else can help refine this code. – Jonathan Gray Nov 03 '14 at 07:38
0

getProjectDetail is a returning a promise, you are calling getProjectDetail inside a for loop. but the for loop is not hold until promise is resolve that means for loop not hold until u get the data from the getProjectDetail() and for-loop will progress.

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92