核心提示:直接上代码var getJSON = function(url) {var promise = new Promise(function(resolve, reject){var client = n...
直接上代码
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.statusText));
}
};
});
return promise;
};
getJSON("/posts.json").then(function(json) {
console.log('Contents: ' + json);
}, function(error) {
console.error('出错了', error);
});
promise还有个all方法,传入一个promise数组,直接上代码,这是一段nodejs代码,用于处理异步数据,前台也一样用,都是一个道理。
| function getPageAsync(url){ | |
| return new Promise(function(resolve,reject){ | |
| console.log('正在爬取'+url); | |
| http.get(url,function(res){ | |
| var html = ''; | |
| res.on('data',function(data){ | |
| html+=data; | |
| }) | |
| res.on('end',function(){ | |
| resolve(html); | |
| //var courseData = filterChapters(html); | |
| //printCourseInfo(courseData); | |
| }) | |
| }).on('error',function(e){ | |
| reject(e); | |
| console.log('获取数据出错!') | |
| }) | |
| }) | |
| } | |
| var fetchCourseArray = []; | |
| videoIds.forEach(function(id){ | |
| fetchCourseArray.push(getPageAsync(baseUrl+id)); | |
| }); | |
| Promise | |
| .all(fetchCourseArray) | |
| .then(function(pages){ | |
| var coursesData = []; | |
| pages.forEach(function(html){ | |
| var courses = filterChapters(html); | |
| coursesData.push(courses); | |
| }) | |
| coursesData.sort(function(a,b){ | |
| return a.number |
|
| }) | |
| printCourseInfo(coursesData); | |
| }); |


