嘛。如果允許使用jQuery -jquery promise接口和jQuery.Deferred就是這樣的東西:
// Create a Deferred and return its Promise
function asyncEvent(){
var dfd = new jQuery.Deferred();
setTimeout(function(){
dfd.resolve("hurray");
}, Math.floor(Math.random()*1500));
setTimeout(function(){
dfd.reject("sorry");
}, Math.floor(Math.random()*1500));
return dfd.promise();
}
// Attach a done and fail handler for the asyncEvent
$.when(asyncEvent()).then(
function(status){
alert(status+', things are going well');
},
function(status){
alert(status+', you fail this time');
}
);
另一個例子;
function doAjax(){
return $.get('foo.htm');
}
function doMoreAjax(){
return $.get('bar.htm');
}
$.when(doAjax(), doMoreAjax())
.then(function(){
console.log('I fire once BOTH ajax requests have completed!');
})
.fail(function(){
console.log('I fire if one or more requests failed.');
});
什麼是'異步classes'? – davin
@達文,修正了問題 – Kyle