es6 promise用法

3 篇文章 0 订阅

直接上代码

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<b.number
  })
  printCourseInfo(coursesData);
  });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值