promise应用于ajax,可以在本页打开控制台,复制代码试验
var url = 'https://www.cnblogs.com/mvc/blog/news.aspx?blogApp=dkplus';
var url1 = 'https://www.cnblogs.com/mvc/blog/calendar.aspx?blogApp=dkplus&dateStr=';
function getJSON(url) {
return new Promise(function(resolve, reject) {
var XHR = new XMLHttpRequest();
XHR.open('GET', url, true);
XHR.send();
XHR.onreadystatechange = function() {
if (XHR.readyState == 4) {
if (XHR.status == 200) {
try {
var response = XHR.responseText;
resolve(response);
} catch (e) {
reject(e);
}
} else {
reject(new Error(XHR.statusText));
}
}
}
})
}
function renderAll() {
return Promise.all([getJSON(url), getJSON(url1)]);
}
// 全部成功
renderAll().then(function(value) {
console.log(value);
})
function renderRace() {
return Promise.race([getJSON(url), getJSON(url1)]);
}
// 有数据返回的时候
renderRace().then(function(value) {
console.log(value);
})