To maintain the scope of the name
variable, you can use .queue()
and $.map()
. It is also advisable to change the status
array to an object with a property named status
, which has a value of an array. This prevents any potential conflicts with this.status
within the Person
object.
You can also chain the .promise(/* queueName */)
method to execute tasks within the .then()
function once all functions in the specified queue, for example, "status"
, have been called and the length of the queue is equal to zero.
function Person(name, status){
this.name = name;
this.status = status;
}
var blob = new Blob(['{"stream":null}'], {type:"application/json"});
var url = URL.createObjectURL(blob);
// change `status` array reference, e.g., to `arr`
var arr = {status:[]};
var array = ["bill","bob","carl","ton"];
$(arr).queue("status", $.map(array, function(curr) {
return function(next) {
var name = curr;
// do asynchronous stuff
$.ajax({url:url, dataType:"json"})
.then(function(data) {
if(data.stream == null){
var person = new Person(name, "dead");
console.log(name, person);
arr.status.push(person);
}
})
.then(next) // call next function in `"status"` queue
}
}))
.dequeue("status")
.promise("status")
// do stuff when all functions in `"status"` queue have completed,
// `"status"` queue `.length` is `0`
.then(function() {
// `this` : `arr` as jQuery object
// `this[0].status`: array containing objects pushed to `arr.status`
console.log(this[0].status); // $(this).prop("status");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
jsfiddle https://jsfiddle.net/nnayjckc/2/
An alternative approach is to use $.when()
, .apply()
, and $.map()
to achieve the same result.
function Person(name, status) {
this.name = name;
this.status = status;
}
var blob = new Blob(['{"stream":null}'], {
type: "application/json"
});
var url = URL.createObjectURL(blob);
// change `status` array reference, e.g., to `arr`
var arr = {
status: []
};
var array = ["bill", "bob", "carl", "ton"];
$.when.apply($, $.map(array, function(curr) {
var name = curr;
return $.ajax({
url: url,
dataType: "json"
})
.then(function(data) {
if (data.stream == null) {
var person = new Person(name, "dead");
console.log(name, person);
arr.status.push(person);
}
})
}))
.then(function() {
console.log(arr.status)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
jsfiddle https://jsfiddle.net/nnayjckc/3/