promise学习笔记

本文大部分内容来自阮一峰的ES6入门 这里针对个人所需记录的笔记,如需全面浏览请转自上述链接

Promise含义

Promise简单来说就是一种容器,里面保存着异步操作的结果.promise对象有以下两个特点

  1. 对象的状态不受外界影响,Promise有三种状态,Pending(进行),Resolved(已完成),Rejected(已失败).只有异步操作的结果才能决定当前是哪一种状态,其他任何操作都无法改变这个状态
  2. 一旦状态改变,就不会再改变.Promise状态的改变只有两种可能,从pending变为Resolved和从Pending变为Rejected.一旦这两种情况发生,状态就凝固了,会一直保持这个结果.就算在对Promise对象添加回调函数,也会立即得到这个结果

基本用法

Promise对象是一个构造函数,用来生成Promise实例

var promise=new Promise(function(resolve,reject){ 
   //...some code 
   if(/* 异步操作成功 */){ 
       resolve(value); 
   }else{ 
       reject(error) 
   } 
}) 

resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”(即从Pending变为Resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”(即从Pending变为Rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。

Promise实例生成以后,可以用then方法分别指定Resolved状态和Reject状态的回调函数。

promise.then(function(value){ 
   //这是resolve触发的事件 
},function(value){ 
   //这是reject触发的事件 
}) 

下面是一个Promise对象简单的例子

function timeout(ms){ 
   return new Promise((resolve,reject)=>{ 
       setTimeout(resolve,ms,"done"); 
   }) 
} 
timeout(100).then((value)={console.log(value)}) 

当经过100毫秒后就会触发resolve事件.Promise新建后就会立即执行

let promise = new Promise(function(resolve, reject) { 
 console.log('Promise'); 
 resolve(); 
}); 

promise.then(function() { 
 console.log('Resolved.'); 
}); 

console.log('Hi!'); 

// Promise 
// Hi! 
// Resolved 

上面代码中,Promise新建后立即执行,所以首先输出的是“Promise”。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以“Resolved”最后输出。

下面是异步加载图片的例子。

function loadImageAsync(url){ 
   return new Promise(function(resolve,reject){ 
       var image=new Image(); 
       image.onload=function(){ 
           resolve(image) 
       } 
       image.onerror=function(){ 
           reject(new Error("Could not load image at "+url)) 
       } 
       image.src=url; 
   }) 
} 

下面是一个用Promise实现Ajax操作的例子

var getJSON=function(url){ 
   var promise=new Promise(function(resolve,reject){ 
           var client=new XMLHttpRequest(); 
           client.open("GET",url); 
           client.onreadstatechange=handler; 
           client.responseType="json"; 
           client.sendRequestHeader("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)) 
               } 
           } 
   }) 
} 

getJSON("/xx.json").then(function(json){ 
   console.log('Content:'+json) 
},function(error){ 
   console.log("出错了",error) 
}) 

上面代码中,getJSON是对XMLHttpRequest对象的封装,用于发出一个针对JSON数据的HTTP请求,并且返回一个Promise对象。需要注意的是,在getJSON内部,resolve函数和reject函数调用时,都带有参数。

如果调用resolve函数和reject函数时带有参数,那么它们的参数会被传递给回调函数。reject函数的参数通常是Error对象的实例,表示抛出的错误;resolve函数的参数除了正常的值以外,还可能是另一个Promise实例,表示异步操作的结果有可能是一个值,也有可能是另一个异步操作,比如像下面这样。

var p1=new Promise(function(resolve,reject){ 
   setTimeout(resolve,2000) 
}) 

var p2=new Promise(function(resolve,reject){ 
   resolve(p1) 
}) 

p2.then(()=>{console.log("hello,p1 is done")}); 

上面代码中,p1和p2都是Promise的实例,但是p2的resolve方法将p1作为参数,即一个异步操作的结果是返回另一个异步操作。注意,这时p1的状态就会传递给p2,也就是说,p1的状态决定了p2的状态。如果p1的状态是Pending,那么p2的回调函数就会等待p1的状态改变;如果p1的状态已经是Resolved或者Rejected,那么p2的回调函数将会立刻执行。

var p1 = new Promise(function (resolve, reject) { 
 setTimeout(() => reject(new Error('fail')), 3000) 
}) 
var p2 = new Promise(function (resolve, reject) { 
 setTimeout(() => resolve(p1), 1000) 
}) 
p2.then(result => console.log(result)) 
p2.catch(error => console.log(error)) 

上面代码中,p1是一个Promise,3秒之后变为rejected。p2的状态由p1决定,1秒之后,p2调用resolve方法,但是此时p1的状态还没有改变,因此p2的状态也不会变。又过了2秒,p1变为rejected,p2也跟着变为rejected。

Promise.prototype.then()

then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。

getJSON("/posts.json").then(function(json) { 
 return json.post; 
}).then(function(post) { 
 // ... 
}); 

上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。采用链式的then,可以指定一组按照次序调用的回调函数。这时,前一个回调函数,有可能返回的还是一个Promise对象(即有异步操作),这时后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。

getJSON("/post/1.json").then(function(post) { 
 return getJSON(post.commentURL); 
}).then(function funcA(comments) { 
 console.log("Resolved: ", comments); 
}, function funcB(err){ 
 console.log("Rejected: ", err); 
}); 

then可以返回一个promise对象

//then返回一个promise 
let test1=function(id){ 
   let promise=new Promise(function(resolve,reject){ 
       setTimeout(()=>{ 
           resolve(id) 
       },1000) 
   }); 
   return promise 
}; 
test1(123) 
   .then((id)=>{console.log("your id",id);return test1(456)}) 
   .then((id)=>{console.log("your id",id);return test1(789)}); 

每次执行完毕后都返回一个新的promise对象,于是就可以实现then连续调用

Promise.prototype.catch()

Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数。

getJSON("/posts.json").then(function(posts) { 
 // ... 
}).catch(function(error) { 
 // 处理 getJSON 和 前一个回调函数运行时发生的错误 
 console.log('发生错误!', error); 
}); 

then方法指定的回调函数,如果运行中抛出错误,也会被catch方法捕获。

var promise = new Promise(function(resolve, reject) { 
 throw new Error('test'); 
}); 
promise.catch(function(error) { 
 console.log(error); 
}); 
// Error: test 

上面代码中,promise抛出一个错误,就被catch方法指定的回调函数捕获。注意,上面的写法与下面两种写法是等价的。

/ 写法一 
var promise = new Promise(function(resolve, reject) { 
 try { 
   throw new Error('test'); 
 } catch(e) { 
   reject(e); 
 } 
}); 
promise.catch(function(error) { 
 console.log(error); 
}); 

// 写法二 
var promise = new Promise(function(resolve, reject) { 
 reject(new Error('test')); 
}); 
promise.catch(function(error) { 
 console.log(error); 
}); 

如果状态已经变为resolved那么再抛出错误是无效的

var promise = new Promise(function(resolve, reject) { 
 resolve('ok'); 
 throw new Error('test'); 
}); 
promise 
 .then(function(value) { console.log(value) }) 
 .catch(function(error) { console.log(error) }); 

Promise对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。

getJSON("/post/1.json").then(function(post) { 
 return getJSON(post.commentURL); 
}).then(function(comments) { 
 // some code 
}).catch(function(error) { 
 // 处理前面三个Promise产生的错误 
}); 

我们改写下test1这个函数 使他能够抛出错误

//then返回一个promise 
let test1=function(id,err){ 
   let promise=new Promise(function(resolve,reject){ 
       setTimeout(()=>{ 
           if(err){ 
               reject(new Error(err)) 
           } 
           resolve(id) 
       },1000) 
   }); 
   return promise 
}; 
test1(123) 
   .then((id)=>{console.log("your id",id);return test1(456)}) 
   .then((id)=>{console.log("your id",id);return test1(789,"我是789中的error")}) 
   .then((id)=>{console.log("your id",id);return test1([10,11,12])}) 
   .catch((error)=>{console.log("出错了,错误为",error)}); 

只要当then过程中有一个reject那么剩下的then都不会继续执行,转而是调用catch这个函数,上述的代码会阻止下面其他代码的运行 因为报错了

跟传统的try/catch代码块不同的是,如果没有使用catch方法指定错误处理的回调函数,Promise对象抛出的错误不会传递到外层代码,即不会有任何反应。

var someAsyncThing = function() { 
   return new Promise(function(resolve, reject) { 
       // 下面一行会报错,因为x没有声明 
       resolve(x + 2); 
   }); 
}; 

someAsyncThing().then(function() { 
   console.log('everything is great'); 
}); 

上述的代码执行不会有任何的反应,也不会报错除非自己手动添加catch函数

someAsyncThing().then(function() { 
   console.log('everything is great'); 
});.catch((err)=>{console.log(err)}); 

上述代码执行会报错[ReferenceError: x is not defined]

var p3 = new Promise(function(resolve, reject) { 
   resolve("ok"); 
   setTimeout(function() { throw new Error('test') }, 0) 
}); 
p3.then(function(value) { console.log(value) }); 

上面代码中,Promise指定在下一轮“事件循环”再抛出错误,结果由于没有指定使用try…catch语句,就冒泡到最外层,成了未捕获的错误。因为此时,Promise的函数体已经运行结束了,所以这个错误是在Promise函数体外抛出的。并且阻止了下面语句的运行需要注意的是,catch方法返回的还是一个Promise对象,因此后面还可以接着调用then方法。

var someAsyncThing = function() { 
 return new Promise(function(resolve, reject) { 
   // 下面一行会报错,因为x没有声明 
   resolve(x + 2); 
 }); 
}; 

someAsyncThing() 
.catch(function(error) { 
 console.log('oh no', error); 
}) 
.then(function() { 
 console.log('carry on'); 
}); 

用catch捕获后的错误会阻塞运行,但是如果在catch后面再跟上then就可以在错误报出后继续运行,并且可以用catch来捕获catch中抛出的错误。

Promise.all()

var p =Promise.all([p1,p2,p3]) 

Promise.all方法的参数可以不是数组,但必须具有Iterator接口,且返回的每个成员都是Promise实例。p的状态由p1、p2、p3决定,分成两种情况。

  1. 只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。
  2. 只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

举个例子

let promiseAll=Promise 
   .all([test1("i m test1"),test1("i m test2","the test2 error"),test1("i m test3")]) 
   .then((id)=>{console.log(id)}).catch((err)=>{console.log(err)}); 

只要有一个test1函数为reject,那么就不会执行then

Promise.race()

var p = Promise.race([p1,p2,p3]); 

上面代码中,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的Promise实例的返回值,就传递给p的回调函数。

Promise.race方法的参数与Promise.all方法一样,如果不是Promise实例,就会先调用下面讲到的Promise.resolve方法,将参数转为Promise实例,再进一步处理。

下面是一个例子,如果指定时间内没有获得结果,就将Promise的状态变为reject,否则变为resolve。

var p = Promise.race([ 
 fetch('/resource-that-may-take-a-while'), 
 new Promise(function (resolve, reject) { 
   setTimeout(() => reject(new Error('request timeout')), 5000) 
 }) 
]) 
p.then(response => console.log(response)) 
p.catch(error => console.log(error)) 

上面代码中,如果5秒之内fetch方法无法返回结果,变量p的状态就会变为rejected,从而触发catch方法指定的回调函数。跟Promise.all差不多,区别就是race只要有一个promise改变后就不会执行其他的promise函数,类似于and与or的区别

Promise.resolve()

将现有对象转换为Promise对象.

var jsPromise = Promise.resolve($.ajax('/whatever.json')); 

上面代码将jQuery生成的deferred对象,转为一个新的Promise对象。

Promise.resolve等价于下面的写法。

Promise.resolve('foo') 
// 等价于 
new Promise(resolve => resolve('foo')) 

  1. 参数是一个Promise实例如果参数是Promise实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。

  2. 参数是一个thenable对象thenable对象指的是具有then方法的对象,比如下面这个对象。
    12345let thenable = { then: function(resolve, reject) { resolve(42); }};

Promise.resolve方法会将这个对象转为Promise对象,然后就立即执行thenable对象的then方法。

let thenable = { 
 then: function(resolve, reject) { 
   resolve(42); 
 } 
}; 

let p1 = Promise.resolve(thenable); 
p1.then(function(value) { 
 console.log(value);  // 42 
}); 

  1. 参数不是具有then方法的对象,或根本就不是对象123456var p = Promise.resolve('Hello');p.then(function (s){ console.log(s)});// Hello

上面代码生成一个新的Promise对象的实例p。由于字符串Hello不属于异步操作(判断方法是它不是具有then方法的对象),返回Promise实例的状态从一生成就是Resolved,所以回调函数会立即执行。Promise.resolve方法的参数,会同时传给回调函数。

  1. 不带有任何参数Promise.resolve方法允许调用时不带参数,直接返回一个Resolved状态的Promise对象。所以,如果希望得到一个Promise对象,比较方便的方法就是直接调用Promise.resolve方法。12345var p = Promise.resolve();p.then(function () { // ...});

上面代码的变量p就是一个Promise对象。并且是Resolved状态 所以回调函数(then)会立即执行

Promise.reject()

Promise.reject()跟Promise.resolve一致,唯一不同的是resolve会返回resolved状态,reject会返回rejected状态

var p = Promise.reject('出错了'); 
// 等同于 
var p = new Promise((resolve, reject) => reject('出错了')) 

p.then(null, function (s){ 
 console.log(s) 
}); 
// 出错了 

两个有用的附加方法

非ES6之中,需要自己部署

done()

Promise对象的回调链,不管以then方法或catch方法结尾,要是最后一个方法抛出错误,都有可能无法捕捉到(因为Promise内部的错误不会冒泡到全局)。因此,我们可以提供一个done方法,总是处于回调链的尾端,保证抛出任何可能出现的错误。

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

为了避免如果最后一个then(f2)出错后Promise的错误无法冒泡到全局 于是可以使用done函数来结束回调链

finally()

finally方法用于指定不管Promise对象最后状态如何,都会执行的操作。它与done方法的最大区别,它接受一个普通的回调函数作为参数,该函数不管怎样都必须执行。

下面是一个例子,服务器使用Promise处理请求,然后使用finally方法关掉服务器。

server.listen(0) 
 .then(function () { 
   // run test 
 }) 
 .finally(server.stop); 

Promise.prototype.finally = function (callback) { 
 let P = this.constructor; 
 return this.then( 
   value  => P.resolve(callback()).then(() => value), 
   reason => P.resolve(callback()).then(() => { throw reason }) 
 ); 
}; 

其中的P指向的是this的构造函数,也就是Promise这个构造函数,该方法如果出错则会执行reason回调,如果正常则会value这个回调函数上面代码中,不管前面的Promise是fulfilled还是rejected,都会执行回调函数callback。

应用

加载图片

const preloadImage = function (path) { 
 return new Promise(function (resolve, reject) { 
   var image = new Image(); 
   image.onload  = resolve; 
   image.onerror = reject; 
   image.src = path; 
 }); 
}; 

这样以后调用的时候只需要

preloadImage("xxx.com/img.png").then(()=>{//onload}).catch(()=>{//onerror}) 

Generator函数与Promise的结合

使用Generator函数管理流程,遇到异步操作的时候,通常返回一个Promise对象

function getFoo(){ 
   return new Promise(function(resolve,reject){ 
       resolve("foo")     
   }) 
} 

var g=function* (){ 
   try{ 
       var foo=yield getFoo(); 
       console.log(foo) 
   }catch(e){ 
       console.log(e) 
   } 
} 

function run (generator){ 
   var it =generator(); 

   function go(result){ 
       if(result.done){ 
           return result.value 
       } 
       return result.value.then((value)=>{return go(it.next(value))}) 
                           .catch((error)=>{return go(it.throw(error))}) 
   } 

   go(it.next()); 

} 

run(g) 

上述代码中利用run来处理流程,首先执行go(it.next()), 其中it.next()会返回一个Promise对象,然后用go函数来处理Promise对象,go函数中进行判断 如果函数执行完毕则会返回这个值,如果没有执行完毕则会继续执行promise对象的then函数.如then函数中的value就是”foo”这个字符串 并且再执行next函数把foo传递给g函数看起来达到同步的效果那么这里的处理业务逻辑在哪呢?就在generator函数中,

var foo=yield getFoo(); 
      console.log(foo) 

这段代码把异步改成同步了,当有返回值的时候则会传递给foo.然后做下一步动作