I'm trying to iterate over an array and assign a variable with a for loop. So something like this:
function Person(name, status){
this.name = name;
this.status = status;
}
var status = [];
var array = ["bill","bob","carl","ton"];
function exAjax(function(){
for(var i = 0; i < array.length; i++){
var name = array[i];
console.log(name); =====> this gives the correct name
$.ajax({
url: xxxxxxx,
success: function(data){
if(data.stream === null){
var person = new Person(name, "dead");
console.log(name); =====> return undefined until the last
person
status.push(person);
}
}
})
name = "";
}
})
The problem I'm having is that name is not getting into the success function. I thought js keeps traveling upwards to look for the variable if it doesn't exist in it's current scope? I'm getting undefined for the name variable if I try to console.log name! Scope masters what am I doing wrong?
That's because
$.ajax
perform an asynchronous HTTP (Ajax) request. It means that yourfor
loop won't wait forsuccess
to complete. Instead it will continue with its iteration.One way (of the many possible solutions), is to make this
$.ajax
synchronous
with theasync: false
optionFrom the documentation
You can use
.queue()
,$.map()
to maintain scope ofname
. Also, changestatus
array to an object having propertystatus
where value is an array to prevent possible conflict withthis.status
ofPerson
object.Note, you can also chain
.promise(/* queueName */)
to perform tasks at.then()
when all queued functions inqueueName
, i.e.g.,"status"
have been called,queueName
.length
is0
.jsfiddle https://jsfiddle.net/nnayjckc/2/
You can alternatively use
$.when()
,.apply()
,$.map()
, to return same resultjsfiddle https://jsfiddle.net/nnayjckc/3/