引言
在经过我的第一个项目之后,我深深体会到了ES6的重要性,以及Promise的重中之重,真的被各种异步问题拷打惨了,所以在经过对他的恶补之后,写了本篇文章,总结一下学习心得。
Promise的含义
Promise可以看成一个容器,里面保存着某个未来才会结束的事件(通常为一个异步操作)的结果;
Promise.resolve()
有时需要将现有对象转为Promise对象,Promise.resolve()方法就起到这个作用。
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
上面代码将jQuery 生成的 deferred 对象,转为一个新的 Promise对象。
Promise.resolve()也等价于下面的写法:
Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))
Promise.resolve 方法的参数分为四种情况:
- 参数为一个Promise 实例
如果参数是Promise实例,那么Promise.resolve 将不做任何修改、原封不动地返回这个实例。
- 参数为一个thenable对象
thenable 对象指的是具有 then 方法的对象:
let 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
});
上面代码中,thenable 对象的 then 方法执行后,对象p1的状态就变为resolved,从而立即执行最后那个 then 方法指定的回调函数。
- 参数不是具有 then 方法的对象,或根本就不是对象
如果参数是一个原始值,或者是一个不具有 then 方法的对象,则 Promise.resolve 方法返回一个新的 Promise 对象,状态为resolved。
const p = Promise.resolve('Hello');
p.then(function (s){
console.log(s)
});
// Hello
上面代码生成一个新的Promise对象的实例p。由于字符串Hello不属于异步操作(判断方法是字符串对象不具有then方法),返回 Promise 实例的状态从一生成就是resolved,所以回调函数会立即执行。
- 不带有任何参数
Promise.resolve() 方法允许调用时不带参数,直接返回一个 resolved 状态的 Promise 对象。
所以,如果希望得到一个 Promise 对象,比较方便的方法就是直接调用 Promise.resolve() 方法。
const p = Promise.resolve();
p.then(function () {
// ...
});
Promise.reject()
Promise.reject(reason)方法也会返回一个新的 Promise 实例,状态为 rejected 。
const p = Promise.reject('出错了');
// 等同于
const p = new Promise((resolve, reject) => reject('出错了'))
p.then(null, function (s) {
console.log(s)
});
// 出错了
上面的代码生成了一个Promise 对象的实例 p ,状态为 rejected ,回调函数会立即执行。
注意,Promise.reject()方法的参数,会原封不动地作为 reject 的理由,变成后续方法的参数。这一点和resolve不一样。
const thenable = {
then(resolve, reject) {
reject('出错了');
}
};
Promise.reject(thenable)
.catch(e => {
console.log(e === thenable)
})
// true
上面代码中, Promise.reject 方法的参数是一个thenable 对象,执行以后,后面 catch 方法的参数不是reject 抛出的“出错了”这个字符串,而是 thenable 对象。
应用
加载图片
我们可以将图片的加载写成一个 Promise ,一旦加载完成,Promise 的状态就发生变化。
const preloadImage = function (path) {
return new Promise(function (resolve, reject) {
const image = new Image();
image.onload = resolve;
image.onerror = reject;
image.src = path;
});
};
Generator 函数与Promise的结合
使用 Generator 函数管理流程,遇到异步操作的时候,通常返回一个 Promise 对象。
function getFoo () {
return new Promise(function (resolve, reject){
resolve('foo');
});
}
const g = function* () {
try {
const foo = yield getFoo();
console.log(foo);
} catch (e) {
console.log(e);
}
};
function run (generator) {
const it = generator();
function go(result) {
if (result.done) return result.value;
return result.value.then(function (value) {
return go(it.next(value));
}, function (error) {
return go(it.throw(error));
});
}
go(it.next());
}
run(g);
上面代码的Generator 函数g之中,有一个异步操作 getFoo ,它返回的就是一个 Promise 对象。函数 run 用来处理这个 Promise 对象,并调用下一个 next 方法。
Promise.try()
在实际开发中,经常会遇到一种情况:不知道或者不想区分,函数 f 是同步函数还是异步函数,但是想用Promise 来处理它。因为这样就可以不管 f 是否包含异步操作,都用 then 方法指定下一步流程,用 catch 方法处理 f 抛出的错误。
一般会这样写:
Promise.resolve().then(f)
但是这种写法存在一种问题,如果 f 是同步函数,经过Promise 包装了之后,就变成了异步执行。
有两种写法可以让同步函数同步执行,异步函数异步执行,一种是用async函数:
const f = () => console.log('now');
(async () => f())();
console.log('next');
// now
// next
在上面的代码中,第2行是一个立即执行的匿名函数,会立即执行里面的 async 函数,当 f 是同步的,就会得到同步的结果,如果 f 是异步的,就可以用 then 来指定下一步。
(async () => f())()
.then(...)
但是,要注意,async ()=> f()会吃掉f()抛出的错误,所以,如果要想捕获错误,就要使用 promise.catch 方法。
(async () => f())()
.then(...)
.catch(...)
第二种就是使用 new Promise()
const f = () => console.log('now');
(
() => new Promise(
resolve => resolve(f())
)
)();
console.log('next');
// now
// next
当然,Promise.try 方法就是用来替代上面的写法的。
const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next
同时,也可以用promise.catch()捕获所有同步和异步的错误。
Promise.try(() => database.users.get({id: userId}))
.then(...)
.catch(...)
Promise的基本用法
ES6规定,Promise 对象是一个构造函数,用来生成Promise 实例。
比如:
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
Promise 构造函数接受一个函数作为参数,该函数的两个参数分别是 resolve 和 reject 。
resolve 函数的作用是,将Promise 对象的状态从”未完成“变为”成功“(即从 pending变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;
reject 函数的作用是,将 Promise 对象的状态从”未完成“变为”失败“(即从 pending 变为 rejected),
在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去;
Promise 实例生成后,可以用 then 方法分别指定 resolved 状态和 rejected 状态的回调函数。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
then 方法可以接受两个回调函数作为参数。第一个回调函数是 Promise 对象的状态变为 resolved 时调用,第二个回调函数是 Promise 对象的状态变为 rejected 时调用。其中,第二个函数是可选的。
举个栗子:
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done');
});
}
timeout(100).then((value) => {
console.log(value);
});
上面的代码中,timeout 方法返回一个 Promise 实例,表示一段时间以后才会发生的结果。当指定时间到了以后,Promise 实例的状态就会变为 resolved ,就会触发 then 方法绑定的回调函数。
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 最后输出。
注意:调用 resolve 或 reject 并不会终结 Promise 的参数函数的执行。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
一般来说,调用 resolve 或 reject之后,Promise 的使命就完成了,后继操作应该放到 then 方法里面,而不应该直接写在resolve 或 reject 后面,所以,最好在他们之前加上return。
new Promise((resolve, reject) => {
return resolve(1);
// 后面的语句不会执行
console.log(2);
})
Promise.prototype.then()
Promise 实例具有 then 方法,也就是说, then 方法是定义在原型对象 Pormise.prototype 上的。它的作用是为Promise实例添加状态改变时的回调函数。
then 方法返回的是一个新的 Promise 实例(注意的是,不是原来那个 Promise 实例)。因此可以采用链式写法,即 then 方法后面再调用另一个 then 方法。
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
Promise.prototype.catch()
Promise.prototype.catch() 方法是 .then(null, rejection) 或 .then(undefined, 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));
如果 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对象抛出的错误都会被最后一个catch所捕获。
一般来说,不要在 then()方法里面定义 Reject 状态的回调函数(即 then 的第二个参数),总是使用 catch 方法。
// 不推荐
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// 推荐
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});
注意的是,如果没有使用 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.prototype.finally()
finally()方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
上面的代码中,不管 promise 最后的状态,在执行完 then 或 catch 指定的回调函数以后,都会执行 finally 方法指定的回调函数。
finally 本质上是 then 方法的特例。
promise
.finally(() => {
// 语句
});
// 等同于
promise
.then(
result => {
// 语句
return result;
},
error => {
// 语句
throw error;
}
);
它的实现也很简单:
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 })
);
};
上面代码中,不管前面的 Promise 是 fulfilled 还是 rejected ,都会执行回调函数 callback。
finally 方法总是会返回原来的值。
// resolve 的值是 undefined
Promise.resolve(2).then(() => {}, () => {})
// resolve 的值是 2
Promise.resolve(2).finally(() => {})
// reject 的值是 undefined
Promise.reject(3).then(() => {}, () => {})
// reject 的值是 3
Promise.reject(3).finally(() => {})
Promise.all()
Promise.all()方法用于将多个Promise实例,包装成一个新的 Promise 实例。
const p = Promise.all([p1, p2, p3]);
上面代码中,Promise.all()方法接受一个数组作为参数,p1、p2、p3都是Promise 实例,如果不是,就会先调用 Promise.resolve 方法,将参数转为 Promise 实例,再进一步处理。
另外,Promise.all()方法的参数可以不是数组,但必须具有Iterator接口,且返回的每个成员都是 Promise 实例。
p 的状态由 p1、p2、p3 决定,分成两种情况。
- 只有 p1、p2、p3 的状态都变成 fulfilled,p 的状态才会变成 fulfilled,此时 p1、p2、p3 的返回值组成一个数组,传递给 p 的回调函数。
- 只要 p1、p2、p3 之中有一个被 rejected ,p 的状态就变成 rejected ,此时第一个被 reject 的实例的返回值,会传递给 p 的回调函数。
// 生成一个Promise对象的数组
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
return getJSON('/post/' + id + ".json");
});
Promise.all(promises).then(function (posts) {
// ...
}).catch(function(reason){
// ...
});
上面代码中,promise 是包含6个Promise 实例的数组,只有这6个实例的状态都变成 fulfilled ,或者其中有一个变为 rejected ,才会调用 Promise.all 方法后面的回调函数。
Promise.race()
Promise.race()方法同样是将多个Promise实例,包装成一个新的Promise实例。
const p = Promise.race([p1, p2, p3]);
但是,跟 .all()方法不一样的是,只要p1、p2、p3之中有一个实例率先改变状态,p的状态就会跟着改变。那个率先改变的 Promise 实例的返回值,就传递给 p 的回调函数。
Promise.allSettled()
Promise.allSettled()方法同样是接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例。只有等到所有这些参数实例都返回结果,不管是 fulfilled 还是 rejected ,包装实例才会结束。
小结一下
后续的内容自我感觉并没有很重要了,因为在我目前的开发经验来说,then、catch、finally这些东西是比较重要的,只有在后面开发过程中被拷打了再去看看那些了(希望不要再出现了);