一:浅谈对Promise的理解

297 阅读9分钟

1.Promise是es6新出的语法,目的就是解决回调地狱的问题,那么什么是回调地狱了?

  我们发现上面代码大量使用了回调函数(将一个函数作为参数传递给另个函数)并且有许多 })结尾的符号,使得代码看起来很混乱。
function callbackFn(callback) {
            setTimeout(function () {
                callback()
            }, 1000)
        }
        callbackFn(function () {
            callbackFn(function () {
                callbackFn(function () {
                    callbackFn(function () { console.log('回调结束') })
                })
            })
        })

常见的回调地狱类型:定时器回调 ajax回调 fs读写文件的回调 以及关于异步请求...

2.第一种使用ES6中的Promise,中文翻译过来承诺,意思是在未来某一个时间点承诺返回数据给你。

(1)那么我们先来看看传统的ajax请求

function ajaxFun(url) {
            var xhr = new XMLHttpRequest();
            xhr.open("get", url, false);
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    //以文本形式返回响应数据
                    var textdata = xhr.responseText;
                    //以xml形式返回响应数据
                    var xmldata = xhr.responseXML;

                } else {
                    console.log(http.responseState)
                }
            };
            return textdata
        }
       console.log(ajaxFun('www.baidu.com'))

(2)利用es6的promise封装ajax请求

function ajaxFun(url) {
           return new Promise((resolve,reject)=>{
            var xhr = new XMLHttpRequest();
            xhr.open("get", url, false);
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                   resolve(xhr.responseText)
                } else {
                    reject(xhr.status)
                }
            };
           })
        }
      ajaxFun(url).then((value)=>{
          console.log(value)
      },(reason)=>{
          console.log(reason)
      })

Promise API

Promise是回调地狱的解决方案之一,我们使用Promise的语法来解决回调地狱的问题,使代码拥有可读性和可维护性(ES6 规定,Promise对象是一个构造函数,用来生成Promise实例,针对所有的异步)。

Promise有三个状态: Pending:异步的事情正在执行;要么成功要么失败,只能改变一次状态

Fulfilled:异步的事情成功了;通过resove()

Rejected:异步的事情失败了;通过reject()

  let p = new Promise(function (resolve, reject) {
            // 此处做一个异步的事情  要么成功要么失败
            resolve('成功的回调')
            // reject('失败的回调')
        })

        //then方法接收2个回调要么成功,要么失败
        p.then((value)=>{
            console.log(value)
        },(reason)=>{
            console.log(reason)
        })
        //catch专门处理失败回调,只有一个失败回调
        p.catch((reason)=>{
            console.log(reason)
        })

(1)Promise函数对象的resolve和reject(是函数对象身上的属性,不是实例属性)Promise.resolve()
Promise.reject() 这俩函数都返回一个promise对象

Promise.resolve:

        //1.分为promise类型(取决于上一个状态)和非poomise类型(下一个promise都是成功的回调) 
     let p1=Promise.resolve('abc') //字符串
     let p1=Promise.resolve(123)   //数值
     let p1=Promise.resolve(
         new Promise((resolve,reject)=>{
            resolve(11)
            // reject(22)  
         })
     )
     console.log(p1)   //p1的then方法的回调结果取决于上一个resolve或则是reject
     p1.then((value)=>{console.log(value)},(reason)=>{console.log(reason)})

Promise.reject:

//1.不管是promise类型还是非promsie类型的参数 结果都是失败的回调
    let p=Promise.reject(521)
     let p=Promise.reject('abc')
     let p=Promise.reject(
         new Promise((resolve,reject)=>{
             resolve(22222)
         })
     )
     console.log(p)
     p.then((value)=>{console.log(value)},(reason)=>{console.log(reason)})

(2)Promise原型对象上的then和catch
Promise.prototype.then()
Promsie.prototype.catch()

1.Promise 构造函数有两个变量== resolve== 用于返回异步执行成功的函数 reject 用于返回异步执行失败的函数。配合then与catch一起使用.

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

3.reject后的东西,一定会进入then中的第二个回调,如果then中没有写第二个回调,则进入catch方法。

4.then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数

Promise中的then第二个参数和catch的区别

首先我们区分几个概念:

  1. reject是用来抛出异常的,catch是用来处理异常的;
  2. reject是Promise的方法,而then和catch是Promise实例的方法(Promise.prototype.then
    和 Promise.prototype.catch)。

一、区别

1.Promise.prototype.then()方法

Promise 实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的作用是为 Promise 实例添加状态改变时的回调函数。then方法的第一个参数是resolved状态的回调函数,第二个参数(可选)是rejected状态的回调函数。

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对象状态发生变化。如果变为resolved,就调用funcA,如果状态变为rejected,就调用funcB。

如果采用箭头函数,上面的代码可以写得更简洁。

getJSON("/post/1.json").then(
post => getJSON(post.commentURL)
).then(
comments => console.log("resolved: ", comments),
err => console.log("rejected: ", err)
);

2.Promise.prototype.catch()方法

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

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

上面代码中,getJSON方法返回一个 Promise 对象,如果该对象状态变为resolved,则会调用then方法指定的回调函数;如果异步操作抛出错误,状态就会变为rejected,就会调用catch方法指定的回调函数,处理这个错误。另外,then方法指定的回调函数,如果运行中抛出错误,也会被catch方法捕获。

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));

下面是一个例子

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

比较上面两种写法,可以发现reject方法的作用,等同于抛出错误。 如果 Promise 状态已经变成resolved,再抛出错误是无效的。

const 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 在resolve语句后面,再抛出错误,不会被捕获,等于没有抛出。因为 Promise 的状态一旦改变,就永久保持该状态,不会再变了。

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

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

上面代码中,一共有三个 Promise 对象:一个由getJSON产生,两个由then产生。它们之中任何一个抛出的错误,都会被最后一个catch捕获。

一般来说,不要在then方法里面定义 Reject 状态的回调函数(即then的第二个参数),总是使用catch方法。

// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
 
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});

上面代码中,第二种写法要好于第一种写法,理由是第二种写法可以捕获前面then方法执行中的错误,也更接近同步的写法(try/catch)。因此,建议总是使用catch方法,而不使用then方法的第二个参数。

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

const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行会报错,因为x没有声明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
console.log('everything is great');
});
setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123

上面代码中,someAsyncThing函数产生的 Promise 对象,内部有语法错误。浏览器运行到这一行,会打印出错误提示ReferenceError: x is not defined,但是不会退出进程、终止脚本执行,2 秒之后还是会输出123。这就是说,Promise 内部的错误不会影响到 Promise 外部的代码,通俗的说法就是“Promise 会吃掉错误”。

一般总是建议,Promise 对象后面要跟catch方法,这样可以处理 Promise 内部发生的错误。catch方法返回的还是一个 Promise 对象,因此后面还可以接着调用then方法。

const 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

上面代码运行完catch方法指定的回调函数,会接着运行后面那个then方法指定的回调函数。如果没有报错,则会跳过catch方法。

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

上面的代码因为没有报错,跳过了catch方法,直接执行后面的then方法。此时,要是then方法里面报错,就与前面的catch无关了。catch方法之中,还能再抛出错误。

const 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]

上面代码中,第二个catch方法用来捕获,前一个catch方法抛出的错误。