前端的一个必学知识之一,Promise对象,是一种用来解决异步编程的方案
特点:
1.对象的状态不受外界影响。Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。
只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。
2.一旦状态改变,就不会再变。任何时候都可以得到这个结果。
状态改变只有两种可能:从pending变为fulfilled和从pending变为rejected。
只要这两种情况发生,状态就凝固了,不会再变了,会一直保持这个结果,称为:定型(resolved)
3.缺点:无法取消,一旦创建便立即执行;必须设置回调函数,否则promise内部会报错,但是不反应到外部来;处于pending状态无法知道当前异步操作处于刚开始状态还是即将完成的状态。
4.基本用法
const promise = new Promise(function(resolve, reject) { // ... some code if (/* 异步操作成功 */){ resolve(value); } else { reject(error); } }); promise.then(function(value) { // success }, function(error) { // failure });//then的第二个参数为可选
举几个例子
function timeout(ms) { return new Promise((resolve, reject) => { //setTImeout的第三个参数,作为resolve函数的参数 setTimeout(resolve, ms, 'done'); }); } //调用函数,值100为setTImeout的时间,若异步状态为fulfilled则返回传递给resolve的值 timeout(100).then((value) => { console.log(value); });
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返回返回异步回调函数,所以执行放在后面,因此Hi提前到第二个执行 */
5.Promise.prototype.then(),
当promise对象返回状态为
resolved
时,则会调用then的回调函数a.其返回的是一个新的promise对象
b.可用链式写法书写,
c.一个promise后面可以跟n个then回调函数
getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // ... }); /* *上面的代码使用then方法,依次指定了两个回调函数。 *第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。 */
6.Promise.prototype.catch()
当promise对象返回的状态为
rejected
时,则会调用catch回调函数a.特点同then函数相同,链式编程,返回值为promise,可以跟进多个catch回调函数
const promise = new Promise(function(resolve, reject) { throw new Error('test');//抛出一个错误,即状态转为reject }); promise.catch(function(error) { console.log(error);// Error: test });
const promise = new Promise(function(resolve, reject) { . . . }).then(function(){. . .})
.then(function(){. . .})
.catch(function(error){//处理前面promise对象以及回调的两个then函数的错误});
几个注意的点,
a.catch函数返回为promise对象,所以后面也可以跟进then函数,但前面的catch函数不会捕获后面的then函数的错误
const promise = new Promise(function(resolve, reject) { . . . })
.catch(function(error){//处理前面promise对象的错误})
.then(function(){...});//这里的then函数的错误不会被catch捕获,
因此一般将catch函数写在所以then函数的后面,方便捕获整个promise及then函数的错误
b.catch函数也可以抛出错误,但catch函数抛出的错误只能由后一个catch函数捕获
const promise = new Promise(function(resolve, reject) { . . . }) .catch(function(error){throw new Error('test');})//catch抛出一个错误 .catch(function(){...});//这里的catch函数可以捕获前面promise的错误以及catch的错误
7.promise.all()
用来将多个promise对象包装成一个promise对象
const p = Promise.all([p1, p2, p3]);
----未完待续---
备注:以上学习参考至https://es6.ruanyifeng.com/#docs/promise#