优秀的编程知识分享平台

网站首页 > 技术文章 正文

技术共享 | 10点说明白ECMAScript 6的Promise函数

nanyue 2024-09-03 16:39:47 技术文章 7 ℃

(1)Promise 含义

Promise 是异步编程的一种解决方案,是一个对象,从它可以获取异步操作的消息。简单说就是一个容器,里面保存着某个未来才会结束的事件的结果。

Promise对象有以下两个特点:

(1)对象的状态不受外界影响。有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。 (2)一旦状态改变,就不会再变,任何时候都可以得到这个结果。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。

Promise缺点:

(1)无法取消Promise,一旦新建它就会立即执行,无法中途取消。 (2)如果不设置回调函数,Promise内部抛出的错误,不会反应到外部。 (3)当处于pending状态时,无法得知目前进展到哪一个阶段(刚刚开始还是即将完成)。

注意:后面的resolved统一只指fulfilled状态,不包含rejected状态。

(2)基本用法

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

var promise = new Promise(function(resolve, reject) {

// ... some code

if (/* 异步操作成功 */){

resolve(value);

} else {

reject(error);

}

});

Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。是两个函数,由 JavaScript 引擎提供,不用自己部署。

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

Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数,rejected函数是可选的,不一定要提供,两个函数都接受Promise对象传出的值作为参数。

promise.then(function(value) {

// success

}, function(error) {

// failure

});

注意,调用resolve或reject并不会终结 Promise 的参数函数的执行。

new Promise((resolve, reject) => {

resolve(1);

console.log(2);

}).then(r => {

console.log(r);

});

// 2

// 1

上面代码中,调用resolve(1)以后,后面的console.log(2)还是会执行,并且会首先打印出来。这是因为立即 resolved 的 Promise 是在本轮事件循环的末尾执行,总是晚于本轮循环的同步任务。

调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面,而不应该直接写在resolve或reject的后面。所以,最好在它们前面加上return语句,这样就不会有意外。 new Promise((resolve, reject) => { return resolve(1); // 后面的语句不会执行

console.log(2); })

(3)Promise.prototype.then()

Promise 实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的作用是为 Promise 实例添加状态改变时的回调函数。

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

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。

(4)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方法捕获。

如果Promise状态已经变成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) });

// ok

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 会吃掉错误”。

(5)Promise.all()

Promise.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。 Promise.all方法的参数可以不是数组,但必须具有 Iterator 接口,且返回的每个成员都是 Promise 实例。

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

p的状态由p1、p2、p3决定,分成两种情况:

(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。

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

// 生成一个Promise对象的数组

var promises = [2, 3, 5, 7, 11, 13].map(function (id) {

return getJSON('/post/' + id + ".json");

});

Promise.all(promises).then(function (posts) {

// ...

}).catch(function(reason){

// ...

});

上面代码中,promises是包含6个 Promise 实例的数组,只有这6个实例的状态都变成fulfilled,或者其中有一个变为rejected,才会调用Promise.all方法后面的回调函数。

注意:如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。

const p1 = new Promise((resolve, reject) => {

resolve('hello');

})

.then(result => result)

.catch(e => e);

const p2 = new Promise((resolve, reject) => {

throw new Error('报错了');

})

.then(result => result)

.catch(e => e);

Promise.all([p1, p2])

.then(result => console.log(result))

.catch(e => console.log(e));

// ["hello", Error: 报错了]

上面代码中,p1会resolved,p2首先会rejected,但是p2有自己的catch方法,该方法返回的是一个新的 Promise 实例,p2指向的实际上是这个实例。该实例执行完catch方法后,也会变成resolved,导致Promise.all()方法参数里面的两个实例都会resolved,因此会调用then方法指定的回调函数,而不会调用catch方法指定的回调函数。

(6)Promise.race()

Promise.race方法同样是将多个Promise实例,包装成一个新的Promise实例。

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

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

const 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方法指定的回调函数。

(7)Promise.resolve()

有时需要将现有对象转为Promise对象,Promise.resolve方法就起到这个作用。

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

Promise.resolve方法的参数分成四种情况:

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

(2)参数是一个thenable对象 thenable对象指的是具有then方法的对象,比如下面这个对象。

let thenable = {

then: function(resolve, reject) {

resolve(42);

}

};

let p1 = Promise.resolve(thenable);

p1.then(function(value) {

console.log(value); // 42

});

Promise.resolve方法会将这个对象转为Promise对象,然后就立即执行thenable对象的then方法。then方法执行后,对象p1的状态就变为resolved,从而立即执行最后那个then方法指定的回调函数,输出42。

(3)参数不是具有then方法的对象,或根本就不是对象 如果参数是一个原始值,或者是一个不具有then方法的对象,则Promise.resolve方法返回一个新的Promise对象,状态为resolved。

let thenable = {

then: function(resolve, reject) {

resolve(42);

}

};

let p1 = Promise.resolve(thenable);

p1.then(function(value) {

console.log(value); // 42

});

上面代码生成一个新的Promise对象的实例p。由于字符串Hello不属于异步操作(判断方法是字符串对象不具有then方法),返回Promise实例的状态从一生成就是resolved,所以回调函数会立即执行。Promise.resolve方法的参数,会同时传给回调函数。 (4)不带有任何参数 Promise.resolve方法允许调用时不带参数,直接返回一个resolved状态的Promise对象。 所以,如果希望得到一个Promise对象,比较方便的方法就是直接调用Promise.resolve方法。

var p = Promise.resolve();

p.then(function () {

// ...

});

上面代码的变量p就是一个Promise对象。

注意:立即resolve的Promise对象,是在本轮“事件循环”(event loop)的结束时,而不是在下一轮“事件循环”的开始时。

setTimeout(function () {

console.log('three');

}, 0);

Promise.resolve().then(function () {

console.log('two');

});

console.log('one');

// one

// two

// three

上面代码中,setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.resolve()在本轮“事件循环”结束时执行,console.log('one')则是立即执行,因此最先输出。

(8)Promise.reject()

Promise.reject(reason)方法也会返回一个新的 Promise 实例,该实例的状态为rejected。

var p = Promise.reject('出错了');

// 等同于

var p = new Promise((resolve, reject) => reject('出错了'))

p.then(null, function (s) {

console.log(s)

});

// 出错了

注意:Promise.reject()方法的参数,会原封不动地作为reject的理由,变成后续方法的参数。这一点与Promise.resolve方法不一致。

const thenable = {

then(resolve, reject) {

reject('出错了');

}

};

Promise.reject(thenable).catch(e => {

console.log(e === thenable)

})

// true

上面代码中,Promise.reject方法的参数是一个thenable对象,执行以后,后面catch方法的参数不是reject抛出的“出错了”这个字符串,而是thenable对象。

(9)两个有用的附加方法

done()

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

asyncFunc()

.then(f1)

.catch(r1)

.then(f2)

.done();

// done的实现代码

Promise.prototype.done = function (onFulfilled, onRejected) {

this.then(onFulfilled, onRejected)

.catch(function (reason) {

// 抛出一个全局错误

setTimeout(() => { throw reason }, 0);

});

};

finally()

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

server.listen(0)

.then(function () {

// run test

}).finally(server.stop);

(10)Promise.try()

由于Promise.try为所有操作提供了统一的处理机制,所以如果想用then方法管理流程,最好都用Promise.try包装一下,可以更好地管理异常。

const f = () => console.log('now');

Promise.try(f);

console.log('next');

// now

// next

Promise.try(database.users.get({id: userId}))

.then(...)

.catch(...)

事实上,Promise.try就是模拟try代码块,就像promise.catch模拟的是catch代码块。

Tags:

最近发表
标签列表