很多時候,我們需要使用ajax請求獲取數據A.并使用A中的數據A.a來進行下一步的Ajax操作…
下面使用promise.prototype.then的鏈式引用來實現
// 首先封裝一個getJSON的方法.
var getJSON = function (url) {var promise = new Promise(function (resolve, reject) {var client = new XMLHttpRequest();client.open("GET", url);client.onreadystatechange = handler;client.responseType = "json";client.setRequestHeader ("Accept", "application/json");client.send();function handler() {if (this.readyState !== 4) {return;}if (this.status === 200) {resolve(this.response);} else {reject(new Error(this.statuText));}};});return promise;
}// 上面函數調用.getJSON(url)即可, 使用.then可以改變Resolved狀態的回調函數
// 鏈式調用如下:
getJSON("post/1.json").then(function(post) {return getJSON(post.commentURL);
}).then(function funcA(comments) {console.log("Resolved: ", comments);
}, function funcB(err) {console.log("Rejected: ", err);
});// 注:首先,調用getJSON異步讀取post/1.json路徑下的數據
// 讀取結果作為參數放在post里面,然后再調用getJSON函數,參數為post.commentURL,讀取post.commentURL路徑的數據
// 若讀取成功執行,函數funcA,否則執行函數funcB....// 下面嘗試使用箭頭函數重寫鏈式調用,,,
getJSON("post/1.json").then(post => getJSON(post.commentURL)
).then(comments => console.log("Resolved: ", comments),err => console.log("Rejected: ", err)
);// 簡潔明了,這個接口還不錯...
參考《ES6標準入門》(第3版) P276、P279