您可以使用
.queue(),
$.map()以保持范围
name。此外,改变
status阵列的具有属性的对象
status,其中值是一个数组,以防止可能出现的冲突
this.status的
Person对象。
请注意,您也可以连接
.promise()在执行任务
.then()时,在所有排队的功能
queueName,IEG,
"status"一直呼吁,
queueName
.length是
0。
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/
您也可以使用
$.when(),
.apply(),
$.map(),返回相同的结果
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/



