目前只有兩件事是在JavaScript是異步的:
- 事件偵聽器
setTimeout
setInterval
AJAX在內部使用事件偵聽器。
所以您做些事情,如:
var xhr = new XMLHTTPRequest();
xhr.addEventlistener('readystatechanged', function() {
console.log(xhr.responseText);
});
如果你有一個回調的工作你的代碼可能是這個樣子:
function do_ajax(url, data, callback) {
var xhr = new XMLHTTPRequest();
xhr.open("POST", url);
xhr.addEventlistener('readystatechanged', function() {
if (xhr.readyState==4 && xhr.status==200) {
callback(xhr.responseText);
}
});
}
do_ajax("service.php", "foo=bar", function (response) {
console.log(response);
});
如果你有非常複雜的異步進程我建議看看Promises。 Here is jQuery's take on promises。
你可以這樣做:
when(async_process()).then(function (result) {
return do_something_asynchronous(result); // <-- the result is a promise
}).done(function (result) { // <-- and the resolved value is the input here
console.log(result);
});
隨着承諾你的代碼可能是這樣的:由於您使用jQuery的
headlines.getRandom(true).then(function (random_headlines) {
return new HeadLine(random_headlines);
}).done(headline) {
console.log("And presto!", headline);
});
這應該給你什麼是可能的一些好的想法:https://github.com/caolan/async/ – bfavaretto