『ES6知识点总结』变量的解构赋值node
本文主要内容以下:
1 Promise是什么?
1.1 特色:
1.2 三种状态:
1.3 用处:
1.4 Promise缺点:
1.5 历史过程
2 生成promise实例
3 promise实例的then()方法
4 resolve函数的参数能够是另外一个Promise实例
5 Promise的方法(多种)
5.1 Promise.all()
5.2 Promise.race()
5.3 Promise.reject(reason)
5.4 Promise.resolve(obj)
6 Promise.prototype.catch()的概念
6.1 尽可能不定义then的reject方法
6.2 catch方法返回的仍是一个Promise对象,所以后面还能够接着调用then方法。
7
7.1 若是前面的promise和then()没有报错,则会跳过catch方法。
7.2 抛错的冒泡性质
7.2.1 若是Promise状态已经变成resolved,再抛出错误是无效的。
7.2.2 Promise在下一轮“事件循环”再抛出错误
7.2.3 若是没有处理错误的回调函数,就没有反应
7.2.4 catch方法之中,还能再抛出错误。
8 node.js的unhandledRejection
9 done()
10 finally()ajax
Promise是什么?
0一、是一个对象,用来传递异步操做的消息。
0二、表明了某个将来才会知道结果的事件(一般是一个异步操做)。
0三、提供一个统一的API,能够进一步处理,控制异步操做。json
特色:数组
0一、对象的状态不受外界影响。promise
0二、表明一个异步操做。服务器
三种状态:app
Pending(进行中) Resolved(已完成,又称Fulfilled) Rejected(已失败)。
(1)默认的Promise对象是等待态(Pending)。
只有异步操做的结果,能够决定当前是哪种状态,任何其余操做都没法改变这个状态。
这也是Promise这个名字的由来,它的英语意思就是“许诺”,表示其余手段没法改变。异步
(2)一旦状态改变了,就不会再变了,会一直保持这个结果。
任什么时候候均可以获得这个结果。async
Promise对象的状态改变,只有两种:函数
从Pending变为Resolved。 从Pending变为Rejected。
这与事件(Event)不一样,事件的特色是,若是你错过了它,再去监听,是得不到结果的。
用处:
用Promise对象能够将异步操做以同步操做的流程表达出来,避免了层层嵌套的回调函数。
能够判断多个异步事件的完成,
Promise缺点:
没法取消Promise,一旦新建它就会当即执行,没法中途取消。
若是不设置回调函数,Promise内部抛出的错误,不会反应到外部。
当处于Pending状态时,没法得知目前进展到哪个阶段(刚刚开始仍是即将完成)。
历史过程
生成promise实例
Promise是一个构造函数,能够生成Promise实例。
接受一个函数A做为参数,该函数A有2个参数,是resolve和reject(拒绝),它们是函数,由JS引擎提供,不用本身部署。
resolve(value)函数的做用是,将Promise对象的状态从“未完成”变为“成功”(即从Pending变为Resolved),在异步操做成功时被调用,并将异步操做的结果,做为本身的参数。
reject(error)函数的做用是,将Promise对象的状态从“未完成”变为“失败”(即从Pending变为Rejected),在异步操做失败时调用,并将异步操做报出的错误,做为本身的参数。
reject函数的参数一般是Error对象的实例,表示抛出的错误。
例子:
reject(new Error(this.statusText));
在promise实例的构造函数中,能够只返回resolve(value)或reject(error);
例子:
let pro = new Promise((resolve,reject)=>{resolve(value)});
写法:
创造了一个Promise实例。
const promise = new Promise(function(resolve, reject) { if ( /* 异步操做成功 */ ) { resolve(value); } else { reject(error); } });
promise实例的then()方法
这个方法在实例的状态改变时会触发它的参数函数。
当promise实例转为成功(Resolved)状态时,触发then()的第一个函数参数。
当promise实例转为失败(Rejected)状态时,触发then()的第二个函数参数。(第二个函数参数可选)
这两个函数参数都接受promise实例传出的值做为参数。也就是resolve(value)和reject(value)的value值。
then()方法是定义在原型对象Promise.prototype上的,被全部promise实例继承。
promise.then( function (value) { // success }, function (value) { // failure } );
箭头函数方式:
promise.then( (value)=>{}, (error)=>{} )
若是then()中有设置新的promise实例,则then()方法返回这个promise对象。
不然将默认构建一个新的promise对象,并继承调用then()方法的promise的状态(成功或失败)。
then方法return返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。
所以能够采用链式写法,即then方法后面再调用另外一个then方法。
这个函数返回undefined,则then()方法构建一个默认的Promise对象,而且这个对象拥有then()方法所属的Promise对象的状态。
var p = new Promise(function (resolve) { resolve();//直接标志执行态 }), temp; temp = p.then(function () { //传入执行态函数,不返回值 }); temp.then(function () { console.log('fulfilled');//拥有p的状态 }); console.log(temp === p);//默认构建的promise,但已经和p不是同一个对象,输出false
若是对应状态所执行的函数返回一个全新的Promise对象,则会覆盖掉当前Promise,代码以下:
var p = new Promise(function (resolve) { resolve();//直接标志执行态 }), temp; temp = p.then(function () { //返回新的promise对象,和p的状态无关 return new Promise(function (resolve, reject) { reject();//标志拒绝态 }); }); temp.then(function () { console.log('fulfilled'); }, function () { console.log('rejected');//输出rejected });
resolve函数的参数能够是另外一个Promise实例
表示当前异步操做的取决于另外一个异步操做的结果。
举个例子来讲,张三到李四家拿钥匙,取决于李四在家不在家。
若是李四在家,那么张三能够成功拿到钥匙。若是李四不在家,张三就拿不到钥匙。
有2个promise实例p1和p2,
p2的resolve(p1),那么,p1的状态决定了p2的状态。
若是p1的状态是Pending,那么p2的回调函数就会等待p1的状态改变,在此以前不会有结果。
若是p1的状态已是Resolved或者Rejected,那么p2的回调函数将会马上执行。
好比像下面这样。
var p1 = new Promise(function(resolve, reject) { // ...}); var p2 = new Promise(function(resolve, reject) { // ... resolve(p1); })
【】例子:
p1是一个Promise,3秒以后变为rejected。p2的状态由p1决定,1秒以后,p2调用resolve方法,可是此时p1的状态尚未改变,所以p2的状态也不会变。又过了2秒,p1变为rejected,p2也跟着变为rejected。
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)) // Error: fail
【】例子:
下面是一个Promise对象的简单例子。
timeout函数中,会返回新生成的Promise实例,其中,定时器setTimeout会在100ms后调用resolve("done");当调用resolve后,触发then绑定的回调函数。
zyx456:'done'是resolve的参数。
等效于:
function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(resolve("done"),ms); }); } timeout(100).then((value) => { console.log(value); });
【】例子:
下面是异步加载图片的例子。
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操做的例子。
getJSON是对XMLHttpRequest对象的封装,用于发出一个针对JSON数据的HTTP请求,而且返回一个Promise对象。
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); });
箭头函数写法:
getJSON("/post/1.json").then( post => getJSON(post.commentURL)).then( comments => console.log("Resolved: ", comments), err => console.log("Rejected: ", err));
Promise的方法(多种)
Promise.all()
【01】用于将多个Promise实例,包装成一个新的Promise实例。
接受一个数组做为参数,数组元素都是Promise实例。
若是参数不是Promise实例,会调用Promise.resolve()转变为Promise实例。
Promise.all()方法的参数不必定是数组,可是必须具备iterator接口,且返回的每一个成员都是Promise实例。
【】返回的新的Promise实例的状态:
全部Promise参数的都变成Resolved,p的状态才会变成Resolved,参数的返回值组成一个数组,传递给p的回调函数。
只要有一个参数被rejected,p的状态就变成rejected,此时第一个reject的实例的返回值,会传递给p的回调函数。
(小z:相似于且操做,且假或真,只有全部的是成功的才能够。你想一想,一系列的操做只有都成功才叫成功。)
var p = Promise.all([p1,p2,p3]);
例子
// 生成一个Promise对象的数组 var promises = [2, 3, 5, 7, 8].map(function(id){return getJSON("/post/" + id + ".json");}); Promise.all(promises).then(function(posts) { // ... }).catch(function(reason){ // ... });
Promise.race()
race:赛跑。
【01】将多个Promise实例,包装成一个新的Promise实例。
返回这个新promise实例,新promise实例的状态为第一个改变的参数实例的状态。它的值也是该参数实例传递出来的值。
03,参数若是不是Promise实例,就会调用Promise.resolve方法,将参数转为Promise实例,再进一步处理。
var p = Promise.race([p1,p2,p3]);
例子:
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))
Promise.reject(reason)
【】会返回一个新的Promise实例,该实例的状态为rejected。
参数reason,会被传递给实例的回调函数。
var p = Promise.reject('出错了'); // 等同于 var p = new Promise((resolve, reject) => reject('foo')) p.then(null, function (s){ console.log(s)});// 出错了
Promise.resolve(obj)
【01】将对象转为Promise对象。
若是参数不是具备then方法的对象(又称thenable对象),则返回一个新的Promise对象,且它的状态为Resolved。
好比:参数为字符串时,不属于异步操做(判断方法是它不是具备then方法的对象),因此等价于Promise构造函数当即执行resolve("str");
03,若是没有参数,能够获得一个Promise对象。
04,若是参数是一个Promise实例,则会被原封不动地返回。
var jsPromise = Promise.resolve($.ajax('/whatever.json'));
Promise.resolve等价于下面的写法。
Promise.resolve('foo') // 等价于 new Promise(resolve => resolve('foo'))
例子:
var p = Promise.resolve('Hello'); p.then(function (s){console.log(s)});// Hello
例子:
var p = Promise.resolve(); p.then(function () { // ...});
Promise.prototype.catch()的概念
【01】是 promise实例.then(null, rejection) 的别名,用于指定发生错误时的回调函数。
【】例子:
getJSON方法返回一个Promise对象,若是该对象状态变为Resolved,则会调用then方法指定的回调函数;
若是异步操做抛出错误,状态就会变为Rejected,就会调用catch方法指定的回调函数,处理这个错误。
getJSON("/posts.json").then(function(posts) { // ... }).catch(function(error) { // 处理前一个回调函数运行时发生的错误 console.log('发生错误!', error); });
例子:
p.then((val) => console.log("fulfilled:", val)).catch((err) => console.log("rejected:", err)); // 等同于 p.then((val) => console.log(fulfilled: ", val)).then(null, (err) => console.log(" rejected: ", err));
例子:
Promise抛出一个错误,就被catch方法指定的回调函数捕获。
var promise = new Promise(function(resolve, reject) { throw new Error('test') }); promise.catch(function(error) { console.log(error) });// Error: test
尽可能不定义then的reject方法
通常来讲,不要在then方法里面定义Reject状态的回调函数(即then的第二个参数),老是使用catch方法。
第二种写法要好于第一种写法,理由是前者更接近同步的写法(try/catch)。
// bad promise .then(function(data) { // success }, function(err) { // error }); // good promise .then(function(data) { //cb // success }).catch(function(err) { // error });
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'); }); // oh no [ReferenceError: x is not defined] // carry on
若是前面的promise和then()没有报错,则会跳过catch方法。
Promise.resolve().catch(function(error) { console.log('oh no', error); }).then(function() { console.log('carry on'); }); // carry on
抛错的冒泡性质
Promise对象的错误具备“冒泡”性质,会一直向后传递,直到被捕获为止。
也就是说,错误老是会被下一个catch语句捕获。
例子:
一共有三个Promise对象:一个由getJSON产生,两个由then产生。它们之中任何一个抛出的错误,都会被最后一个catch捕获。
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL); }).then(function(comments) { // some code
}).catch(function(error) { // 处理前面三个Promise产生的错误
});
若是Promise状态已经变成resolved,再抛出错误是无效的。
Promise在resolve语句后面,再抛出错误,不会被捕获,等于没有抛出。
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) });// ok
Promise在下一轮“事件循环”再抛出错误
结果因为没有指定使用try...catch语句,就冒泡到最外层,成了未捕获的错误。
由于此时,Promise的函数体已经运行结束了,因此这个错误是在Promise函数体外抛出的。
var promise = new Promise(function(resolve, reject) { resolve("ok"); setTimeout(function() { throw new Error('test') }, 0) }); promise.then(function(value) { console.log(value) }); // ok // Uncaught Error: test
若是没有处理错误的回调函数,就没有反应
跟传统的try/catch代码块不一样的是,若是没有使用catch方法指定错误处理的回调函数,Promise对象抛出的错误不会传递到外层代码,即不会有任何反应。
someAsyncThing函数产生的Promise对象会报错,可是因为没有指定catch方法,这个错误不会被捕获,也不会传递到外层代码,致使运行后没有任何输出。
var someAsyncThing = function() { return new Promise(function(resolve, reject) { // 下面一行会报错,由于x没有声明 resolve(x + 2); }); }; someAsyncThing().then(function() { console.log('everything is great'); });
catch方法之中,还能再抛出错误。
catch方法抛出一个错误,由于后面没有别的catch方法了,致使这个错误不会被捕获,也不会传递到外层。
var someAsyncThing = function() { return new Promise(function(resolve, reject) { // 下面一行会报错,由于x没有声明 resolve(x + 2); }); }; someAsyncThing().then(function() { return someOtherAsyncThing(); }).catch(function(error) { console.log('oh no', error); // 下面一行会报错,由于y没有声明 y + 2; }).then(function() { console.log('carry on'); }); // oh no [ReferenceError: x is not defined]
若是改写一下,结果就不同了。
第二个catch方法用来捕获,前一个catch方法抛出的错误。
someAsyncThing().then(function() { return someOtherAsyncThing(); }).catch(function(error) { console.log('oh no', error); // 下面一行会报错,由于y没有声明 y + 2; }).catch(function(error) { console.log('carry on', error); }); // oh no [ReferenceError: x is not defined] // carry on [ReferenceError: y is not defined]
node.js的unhandledRejection
Node.js有一个unhandledRejection事件,专门监听未捕获的reject错误。
unhandledRejection事件的监听函数有两个参数,第一个是错误对象,第二个是报错的Promise实例,它能够用来了解发生错误的环境信息。
process.on('unhandledRejection', function (err, p) { console.error(err.stack)});
done()
Promise对象的回调链,无论以then方法或catch方法结尾,要是最后一个方法抛出错误,都有可能会漏掉(Promise内部的错误不会冒泡到全局)。
所以,咱们能够提供一个done方法,老是处于回调链的尾端,保证抛出任何可能出现的错误。
asyncFunc().then(f1).catch(r1).then(f2).done();
done方法的使用,能够像then方法那样用,提供Fulfilled和Rejected状态的回调函数,也能够不提供任何参数。但无论怎样,done都会捕捉到任何可能出现的错误,并向全局抛出。
实现代码:
Promise.prototype.done = function (resolve, reject) { this.then(resolve, reject).catch(function (reason) { // 抛出一个全局错误 setTimeout(() => { throw reason }, 0); }); };
finally()
finally方法用于指定无论Promise对象最后状态如何,都会执行的操做。
它与done方法的最大区别,它接受一个普通的回调函数做为参数,该函数无论怎样都必须执行。
等效于,运行一个then(),在成功和失败回调函数中,都要运行callback(),
在Promise.resolve()中运行callback()后,在运行then(),返回结果。
下面是一个例子,服务器使用Promise处理请求,而后使用finally方法关掉服务器。
server.listen(0).then(function () { // run test }).finally(server.stop);
它的实现:
Promise.prototype.finally = function(callback) { return this.then( value => Promise.resolve( callback() ).then(() => value), reason => Promise.resolve(callback()).then(() => {throw reason })); };