generator出現(xiàn)之前,想要實現(xiàn)對異步隊列中任務(wù)的流程控制,大概有這么一下幾種方式:
回調(diào)函數(shù)
事件監(jiān)聽
發(fā)布/訂閱
promise對象
第一種方式想必大家是最常見的,其代碼組織方式如下:
function fn(url, callback){ var httpRequest; //創(chuàng)建XHR httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : undefined; httpRequest.onreadystatechange = function(){ if(httpRequest.readystate === 4 && httpRequest.status === 200){ //狀態(tài)判斷 callback.call(httpRequest.responseXML); } }; httpRequest.open("GET", url); httpRequest.send(); } fn("text.xml", function(){ //調(diào)用函數(shù) console.log(this); //此語句后輸出}); console.log("this will run before the above callback."); //此語句先輸出