Promise对象

2017-10-19  本文已影响0人  _花

Promise是一个对象,也是个构造函数,用来传递异步操作的信息,它将异步操作以同步操作的流程表现出来,避免了层层回调函数。

对象的状态不受外部的影响,有3种状态Pending(进行中),Resolved(已完成),Rejected(已失败)

1.Promise对象

接受一个函数作为参数。函数有两个参数resolve,reject,这两个参数是两个函数,可以用then()方法来指定两个函数参数,两个函数接收一个参数,该参数是前一步异步执行返回的结果。

例如:

function (){

  return new Promise(function(resolve,reject){

            $.get(url,function(response){

             .......

 })

}).then(function(res){

        //此时res等于上一步的response

       //函数参数就相当于resolve

},function(res){

          //函数参数就相当于reject

})

2.then方法

返回的是新的一个Promise实例,因此可以采用链式写法,then方法后再调用另一个then方法。

3.catch方法

是在捕获异步操作的错误Rejected状态下的回调函数,写法跟then一样,Promise对象的错误具有冒泡的性质,会一直响后传递,总会被下一个catch语句捕获,例如:

promise.then(function(res){ ..............  }).then(function(res){  ................. }).catch(function(err){ //   error此处也可以是promise对象定义时的错误 })

4.Promise.all()、Promise.race()都是将多个Promise对象合并成一个Promise对象

除了串行执行若干异步任务外,Promise还可以并行执行异步任务。

试想一个页面聊天系统,我们需要从两个不同的URL分别获得用户的个人信息和好友列表,这两个任务是可以并行执行的,用Promise.all()实现如下:

varp1 =newPromise(function(resolve, reject){setTimeout(resolve,500,'P1');});

varp2 =newPromise(function(resolve, reject){setTimeout(resolve,600,'P2');});// 同时执行p1和p2,并在它们都完成后执行then:

Promise.all([p1, p2]).then(function(results){console.log(results);// 获得一个Array: ['P1', 'P2']});

有些时候,多个异步任务是为了容错。比如,同时向两个URL读取用户的个人信息,只需要获得先返回的结果即可。这种情况下,用Promise.race()实现:

varp1 =newPromise(function(resolve, reject){setTimeout(resolve,500,'P1');});

varp2 =newPromise(function(resolve, reject){setTimeout(resolve,600,'P2');});

Promise.race([p1, p2]).then(function(result){console.log(result);// 'P1'});

由于p1执行较快,Promise的then()将获得结果'P1'。p2仍在继续执行,但执行结果将被丢弃。

5.Promise.resolve()

Promise.resolve()方法就是将现有对象(或者数字,字符串,数组等)转化成Promise对象,且转化后的Promise对象状态为Resolved。

Promise.reject()方法性质类似

6.附加方法

done()    总是处于回调链的尾端,保证抛出任何可能出现的错误。

finally()     用于指定不管Promise对象最后状态如何都会执行方法,他接受一个函数做参数;

Promise.prototype.done =function(onFulfilled, onRejected){this.then(onFulfilled, onRejected) .catch(function(reason){// 抛出一个全局错误setTimeout(() => {throwreason },0); });};

Promise.prototype.finally =function(callback){letP =this.constructor;returnthis.then( value => P.resolve(callback()).then(() => value), reason => P.resolve(callback()).then(() => {throwreason }) );};

上一篇 下一篇

猜你喜欢

热点阅读