ES6---Promise简析和请求封装

1、Promise的特点

    a、Promise是异步编程的一种解决方案。
    b、Promise的状态不受外部影响,一旦建立就会立即执行,无法中途取消;
    c、一旦状态发生改变之后就不会改变。

2、Promise状态

    a、pending(操作进行中),在此时无法得知目前处于哪个阶段(是开始还是完成阶段);
    b、fulfilled(已经完成),也可以是resolve阶段;
    c、rejected(已经失败)

3、promise实例

下面以封装的ajax请求为基础来对Promise构造函数和promise对象进行解读。

function httpPost (url,params) {
    params = JSON.stringify(params);
    function Cons (resolve,reject) {
        const handler = function () {
            if (this.readyState !== 4) {
                  return
            }
           if (this.status === 200 || this.status === 304) {
                  resolve(this.response);
           } else {
                  reject(new Error(this.statusText))
           }
        }
        const xhr = new XMLHttpRequest();
        xhr.open("POST",url);
        xhr.onreadystatechange = handler;
        xhr.resposeType = 'json';
        xhr.setRequestHeader('Accept','application/json');
        xhr.send(params);
     }
     const promiseObj = new Promise(Cons);
     return promiseObj;
}
httpPost('http://game.bizpartner.cn/gamePrizeActivity/findZiGe',{type: 'ch',page:1,token:"4979f69dabe042f1b0c03a2cf696d6ce"})
     .then(res=>console.log(res))
     .catch(err=>console.log(err))

代码解读:
1、promise对象的构造函数Promise参数:
a、resolve函数:将Promise的状态从pending变为resolved,同时将异步操作的结果传递出去;
b、reject函数:将Promise的状态从pending变为rejected,并将操作中的错误以参数的形式传递出去。

4、Promise原型的方法

    a、then
    Promise.prototype.then()

// 不提倡这样写
httpPost('/game2',{type:2})
        .then(function(resolve){
            console.log('请求成功');
        },function(reject){
            console.log('请求失败');
        })

以上代码解读:
1、promise对象的then方法的参数有两个,一个是resolve状态下的回调,另一个是rejected状态下的回调。rejected状态下的回调是可以省略掉的。
2、因为then返回的是一个新的promise函数,所以可以使用链式方法来写。代码如下:

httpPost('/game2',{type:2})
        .then(function(resolve){
            console.log('请求成功');
        })
        .then(function(reject){
            console.log('请求失败');
        })
b、catch

    Promise.prototype.catch()

httpPost('/game2',{type:2})
        .then(function(resolve){
            console.log('请求成功');
        })
        .catch(function(reject){
            console.log('请求失败');
        })

该方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数。回调中抛出错误,也会被catch方法捕获。

c、resolve

    Promise.resolve()

如果有需要将对象转化为Promise对象,Promise.resolve();

Promise.resolve(console.log('oo'));
||
||      等价于
VV
new Promise(resolve=>console.log('pp'));
d、reject

    Promise.reject()

该方法返回的也是一个新的promise实例,该实例的状态是rejected。

const thenable = {
  then(resolve, reject) {
    reject('出错了');
  }
};

Promise.reject(thenable)
.catch(e => {
  console.log(e === thenable)
})

本文暂时只对四个方法进行解读,除此之外还有all、finally、race、try等方法,有兴趣的朋友有可以参照文档学习。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值