Promise对象

ECMAScript 6 ,允许对延时和异步操作流进行控制
Promise 对象有以下几种状态:
- pending (进行中): 初始的状态,即正在执行,不处于 fulfilled 或 rejected 状态。
- fulfilled (已完成): 成功的完成了操作。
- rejected (已失败): 失败,没有完成操作。
- settled (已解决): Promise 处于 fulfilled 或 rejected 二者中的任意一个状态, 不会是 pending。
来源: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Promises
案例一:

'use strict';
var PromiseCount =0;
function testPromise(){
  var thisPromiseCount =++PromiseCount;
  var log = document.getElementById('log');
  log.insertAdjacentHTML('beforeend',thisPromiseCount+')开始(同步代码开始)<br/>');
  // 构造器内参数----ececutor函数,初始化异步工作
  var p1 = new Promise(function(resolve,reject){        log.insertAdjacentHTML('beforeend',thisPromiseCount+')Promise开始(异步代码开始)<br/>');
   window.setTimeout(function(){
     resolve(thisPromiseCount);
   },Math.random()*2000+1000);
  });
  p1.then(function(val){
  log.insertAdjacentHTML('beforeend',val+')Promise被满足了(异步代码结束)<br/>');
  });
  log.insertAdjacentHTML('beforeend',thisPromiseCount+')建立了Promise(同步代码结束)<br/>')
}

分析总结:
1. 页面点击按钮,testPromise函数执行起来,同步代码开始
2. 创建Promise构造器,里面的函数开始运行,初始化异步工作
3. 函数内有一个异步函数–setTimeout(),当函数运行完, promise对象状态改变,Promise.then中代码开始执行,异步结束
4. 同步代码不会被异步代码中断,顺序执行到结束

案例二:(文件需要一张图片)

 function imgLoad(url) {
    // Create new promise with the Promise() constructor;
    // This has as its argument a function
    // with two parameters, resolve and reject
    return new Promise(function(resolve, reject) {
       // Standard XHR to load an image
      var request = new XMLHttpRequest();
      request.open('GET', url);
      request.responseType = 'blob';
       // When the request loads, check whether it was successful
      request.onload = function() {
        if (request.status === 200) {
        // If successful, resolve the promise by passing back the request response
           resolve(request.response);
        } else {
        // If it fails, reject the promise with a error message
          reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
        }
      };
      request.onerror = function() {
      // Also deal with the case when the entire request fails to begin with
      // This is probably a network error, so reject the promise with an appropriate message
        reject(Error('There was a network error.'));
      };
      // Send the request
      request.send();
    });
}
  // Get a reference to the body element, and create a new image object
  var body = document.querySelector('body');
  var myImage = new Image();
  // Call the function with the URL we want to load, but then chain the
   // promise then() method on to the end of it. This contains two callbacks
  imgLoad('m.jd.com-(iPhone 6 Plus).png').then(function(response) {
     // The first runs when the promise resolves, with the request.reponse
     // specified within the resolve() method.
     var imageURL = window.URL.createObjectURL(response);
     myImage.src = imageURL;
     body.appendChild(myImage);
     // The second runs when the promise
     // is rejected, and logs the Error specified with the reject() method.
     alert('successful');
    }, function(Error) {
     console.log(Error);
  });

发起一个异步请求时,返回一个promise对象,如果成功调用resolve(request.response);返回请求数据,如果失败,调用reject(Error(‘Image didn\’t load successfully; error code:’ + request.statusText));
总结:与案例一类似,当图片加载完成,也就是异步代码执行完之后,Promise 状态改变,Promise.then中代码开始执行。
new Promise()中函数中的异步代码是一个异步的ajax请求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值