JavaScript异步promise详解
什么是Promise?我们用Promise来解决什么问题?
pending
:初始状态,未被兑现,也未被拒绝fulfilled
:已兑现,操作完成rejected
:已拒绝,操作失败
promise是用来解决两个问题的:
-
回调地狱,代码难以维护, 常常第一个的函数的输出是第二个函数的输入这种现象
-
promise可以支持多个并发的请求,获取并发请求中的数据
-
这个promise可以解决异步的问题,本身不能说promise是异步的
es6 promise用法大全
在传入的函数中,控制Promise
的状态转换是通过调用它的两个函数参数实现的,通常命名为resolve()
和reject()
。调用resolve()
将状态转换为fulfilled
,调用reject()
将状态转换为rejected
。另外,调用reject()
将抛出错误。
在Promise
后,调用了then
方法,then
方法最多接收两个函数作为参数,第一个参数是状态变为fulfilled
的回调函数,第二个参数是状态变为rejected
的回调函数。
resolve('xxx')中xxx将会传递给then中的data,reject亦同。
new Promise((resolve, reject) => {
const a = 1;
if (a === 1) {
resolve('fulfilled');
} else {
reject('rejected');
}
}).then(
(data) => console.log(data),
rejectedValue => console.log(rejectedValue)//简写
);
// fulfilled
修改一下a
的值,使Promise
的状态转为rejected
,那么then
方法就会执行第二个参数,打印出reject()
方法传来的值:'rejected'
。
另外,如果内部抛出错误,then
方法也会执行第二个函数:
then 链式操作的用法
then(onFulfilled, onRejected) 中接收2个回调函数,成功和失败的回调函数,会根据Promise的状态来判断执行哪个回调函数。
Promise
可以链式调用,不过promise
每次调用 .then
或者 .catch
都会返回一个新的 promise
如果then
中的回调函数:
返回了一个值,如return 2
会被包装成resolve(2)
,那么then返回的Promise是fulfilled
状态,并将返回的值作为fulfilled
状态的回调函数参数值,若没有返回值,回调函数参数值为undefined。
new Promise((resolve, reject) => {
resolve(1);
// reject(-1);
})
.then(value => {//fulfill
console.log('fulfilledValue', value);
return 'Jack';
})
.then(//状态为fulfilled, then的状态只取决于上一层的调用
res => {
console.log('fulfilledValue', res);
},
res => {
console.log('rejectedValue', res);
}
);
// fulfilledValue 1
// fulfilledValue Jack
new Promise((resolve, reject) => {
// resolve(1);
reject(-1);
})
.then(//reject
value => {
console.log('fulfilledValue', value);
return 'Jack';
},
value => {
console.log('rejectedValue', value);
}
)
.then(//状态为fulfilled, then的状态只取决于上一层的调用
res => {
console.log('fulfilledValue', res);
},
res => {
console.log('rejectedValue', res);
}
);
// rejectedValue -1
// fulfilledValue undefined //没有返回值则为undefined
可以看出then的状态只取决于上一层的调用状态
new Promise((resolve, reject) => {
// resolve(1);
reject(-1);
})
.then(value => {
console.log('fulfilledValue', value);//没有第二个参数,不输出
})
.then(null, res => {
console.log('rejectedValue', res);
});
// rejectedValue -1
如果最初的Promise
是rejected
状态,且第一个then
没有第二个函数参数,那么第二个then
就会执行其第二个回调函数,并且参数为最初Promise
的reject
中的参数。
catch的用法
Promise.prototype.catch()
方法用于给Promise
添加拒绝处理程序。这个方法只接收一个参数:onRejected
处理程序。它的行为与调用Promise.prototype.then(undefined, onRejected)
相同。
如下代码,两种等价的写法。
new Promise((resolve, reject) => {
reject('error');
}).catch(error => console.log(error));
// error
new Promise((resolve, reject) => {
reject('error');
}).then(null, error => console.log(error));
// error
p.then((data) => {
console.log('resolved',data);
console.log(somedata); //此处的somedata未定义
})
.catch((err) => {
console.log('rejected',err);
});
效果和写在then的第二个参数里面一样。不过它还有另外一个作用:在执行resolve的回调(也就是上面then中的第一个参数)时,如果抛出异常了(代码出错了),那么并不会报错卡死js,而是会进到这个catch方法中。
Promise中的then、catch、finally 踩坑总结
Promise
的状态一经改变就不能再改变。
1、Promise
的状态一经改变就不能再改变。
const promise = new Promise((resolve, reject) => {
resolve("success1");
reject("error");
resolve("success2");
});
promise
.then(res => {
console.log("then: ", res);
}).catch(err => {
console.log("catch: ", err);
})
结果:
"then: success1"
2、.then
和.catch
都会返回一个新的Promise
。
const promise1 = new Promise((resolve, reject) => {
console.log('promise1')
resolve('resolve1')
})
const promise2 = promise1.then(res => {
console.log(res)
})
console.log('1', promise1);
console.log('2', promise2);
结果:
'promise1'
'1' Promise{<resolved>: 'resolve1'}//返回一个promise,状态为resolve
'2' Promise{<pending>} //then返回一个新的promise,且状态为pending
'resolve1'
3、catch
不管被连接到哪里,都能捕获上层未捕捉过的错误。
const promise = new Promise((resolve, reject) => {
reject("error");
resolve("success2");
});
promise
.then(res => {
console.log("then1: ", res);
}).then(res => {
console.log("then2: ", res);
}).catch(err => {
console.log("catch: ", err);
}).then(res => {
console.log("then3: ", res);
})
结果:
"catch: " "error"
"then3: " undefined
catch
不管被连接到哪里,都能捕获上层未捕捉过的错误。至于then3
也会被执行,那是因为catch()
也会返回一个Promise
,且由于这个Promise
没有返回值,所以打印出来的是undefined
。
4、在Promise
中,返回任意一个非 promise
的值都会被包裹成 promise
对象,例如return 2
会被包装为return Promise.resolve(2)
,没有返回值则为undefined。
Promise.resolve(1)
.then(res => {
console.log(res);
return 2;
})
.catch(err => {
return 3;
})
.then(res => {
console.log(res);
});
结果:
1
2
resolve(1)
之后走的是第一个then
方法,并没有走catch
里,所以第二个then
中的res
得到的实际上是第一个then
的返回值。 且return 2
会被包装成resolve(2)
。
5、Promise
的 .then
或者 .catch
可以被调用多次, 但如果Promise
内部的状态一经改变,并且有了一个值,那么后续每次调用.then
或者.catch
的时候都会直接拿到该值。
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('timer')
resolve('success')//返回success
}, 1000)
})
const start = Date.now();
promise.then(res => {
console.log(res, Date.now() - start)//同一个success
})
promise.then(res => {
console.log(res, Date.now() - start)//同一个success
})
执行结果:
'timer'
'success' 1001
'success' 1002
6、.then
或者 .catch
中 return
一个 error
对象并不会抛出错误,所以不会被后续的 .catch
捕获,参照第4点,return的错误对象被Promise.resolve()包裹。
Promise.resolve().then(() => {
return new Error('error!!!')
}).then(res => {
console.log("then: ", res)
}).catch(err => {
console.log("catch: ", err)
})
"then: " "Error: error!!!"
你可能想到的是进入.catch然后被捕获了错误。 结果并不是这样的,它走的是.then里面:
这也验证了第4点和第6点,返回任意一个非 promise
的值都会被包裹成 promise
对象,因此这里的return new Error('error!!!')
也被包裹成了return Promise.resolve(new Error('error!!!'))
。
如果你抛出一个错误的话,可以用下面👇两的任意一种:
return Promise.reject(new Error('error!!!'));
// or
throw new Error('error!!!')
7、.then
或 .catch
返回的值不能是 promise 本身,否则会造成死循环。
const promise = Promise.resolve().then(() => {
return promise;
})
promise.catch(console.err)
//
Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>
8、.then
或者 .catch
的参数期望是函数,传入非函数则会发生值透传。
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(r=>{console.log(r);return 3333})
.then(console.log)
//
1
3333
第一个then
和第二个then
中传入的都不是函数,一个是数字类型,一个是对象类型,因此发生了透传,将resolve(1)
的值直接传到最后一个then
里。
9、.then
方法是能接收两个参数的,第一个是处理成功的函数,第二个是处理失败的函数,再某些时候你可以认为catch
是.then
第二个参数的简便写法。
前面catch例子
10、.finally
方法也是返回一个Promise
,他在Promise
结束的时候,无论结果为resolved
还是rejected
,都会执行里面的回调函数。
Promise.all()
Promise.all()
方法接收一组异步任务,然后并行执行异步任务,并且在所有异步操作执行完后才执行回调。回调的结果是一个数组。
有了all,你就可以并行执行多个异步操作,并且在一个回调中处理所有的返回数据。
有一个场景是很适合用这个的,一些游戏类的素材比较多的应用,打开网页时,预先加载需要用到的各种资源如图片、flash以及各种静态文件。所有的都加载完后,我们再进行页面的初始化。
案例:
let Promise1 = new Promise(function(resolve, reject){})
let Promise2 = new Promise(function(resolve, reject){})
let Promise3 = new Promise(function(resolve, reject){})
let p = Promise.all([Promise1, Promise2, Promise3])
p.then(funciton(){
// 三个都成功则成功
}, function(){
// 只要有失败,则失败
})
const promiseArray = [1, 2, 3, 4].map(item => new Promise(resolve => resolve(item)));
console.log(promiseArray);
// [ Promise { 1 }, Promise { 2 }, Promise { 3 }, Promise { 4 } ]
Promise.all(promiseArray).then(res => console.log(res));
// [ 1, 2, 3, 4 ]
function runAsync (x) {
const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
return p
}
function runReject (x) {
const p = new Promise((res, rej) => setTimeout(() => rej(`Error: ${x}`, console.log(x)), 1000 * x))
return p
}
Promise.all([runAsync(1), runReject(4), runAsync(3), runReject(2)])
.then(res => console.log(res))
.catch(err => console.log(err))
// 1s后输出
1
3
// 2s后输出
2
Error: 2
// 4s后输出
4
all和race
传入的数组中如果有会抛出异常的异步任务,那么只有最先抛出的错误会被捕获,并且是被then
的第二个参数或者后面的catch
捕获;但并不会影响数组中其它的异步任务的执行。
Promise.race()
谁跑的快,以谁为准执行回调。
.race()
的作用也是接收一组异步任务,然后并行执行异步任务,只保留取第一个执行完成的异步操作的结果,其他的方法仍在执行,不过执行结果会被抛弃。
function runAsync (x) {
const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
return p
}
Promise.race([runAsync(1), runAsync(2), runAsync(3)])
.then(res => console.log('result: ', res))
.catch(err => console.log(err))
执行结果为:
1
'result: ' 1
2
3
//请求某个图片资源
function requestImg(){
var p = new Promise((resolve, reject) => {
var img = new Image();
img.onload = function(){
resolve(img);
}
img.src = 'wrong';
});
return p;
}
//延时函数,用于给请求计时
function timeout(){
var p = new Promise((resolve, reject) => {
setTimeout(() => {
reject('图片请求超时');
}, 5000);
});
return p;
}
Promise.race([requestImg(), timeout()]).then((data) =>{
console.log(data);//没有输出,无第二个参数
}).catch((err) => {
console.log(err);//图片请求超时
});
Promise中的all和race 踩坑总结
Promise.all()
的作用是接收一组异步任务,然后并行执行异步任务,并且在所有异步操作执行完后才执行回调(全部成功才成功,其中一个失败则失败)。.race()
的作用也是接收一组异步任务,然后并行执行异步任务,只保留取第一个执行完成的异步操作的结果,其他的方法仍在执行,不过执行结果会被抛弃。Promise.all().then(res=>console.log(res))
结果中数组的顺序和Promise.all()
接收到的数组顺序一致。all和race
传入的数组中如果有会抛出异常的异步任务,那么只有最先抛出的错误会被捕获,并且是被then
的第二个参数或者后面的catch
捕获;但并不会影响数组中其它的异步任务的执行。
手写Promise
Promise的核心逻辑实现(部分)
分析一下基本原理:
Promise 是一个类,在执行这个类的时候会传入一个执行器,这个执行器会立即执行 Promise 会有三种状态
- Pending 等待
- Fulfilled 完成
- Rejected 失败
状态只能由 Pending --> Fulfilled 或者 Pending --> Rejected,且一但发生改变便不可二次修改; Promise 中使用 resolve 和 reject 两个函数来更改状态; then 方法内部做但事情就是状态判断
- 如果状态是成功,调用成功回调函数
- 如果状态是失败,调用失败回调函数
// MyPromise.js
// 先定义三个常量表示状态
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
// 新建 MyPromise 类
class MyPromise {
constructor(executor){
// executor 是一个执行器,进入会立即执行
// 并传入resolve和reject方法
executor(this.resolve, this.reject)
}
// 储存状态的变量,初始值是 pending
status = PENDING;
// resolve和reject为什么要用箭头函数?
// 如果直接调用的话,普通函数this指向的是window或者undefined
// 用箭头函数就可以让this指向当前实例对象
// 成功之后的值
value = null;
// 失败之后的原因
reason = null;
// 更改成功后的状态
resolve = (value) => {
// 只有状态是等待,才执行状态修改
if (this.status === PENDING) {
// 状态修改为成功
this.status = FULFILLED;
// 保存成功之后的值
this.value = value;
}
}
// 更改失败后的状态
reject = (reason) => {
// 只有状态是等待,才执行状态修改
if (this.status === PENDING) {
// 状态成功为失败
this.status = REJECTED;
// 保存失败后的原因
this.reason = reason;
}
}
then(onFulfilled, onRejected) {
// 判断状态
if (this.status === FULFILLED) {
// 调用成功回调,并且把值返回
onFulfilled(this.value);
} else if (this.status === REJECTED) {
// 调用失败回调,并且把原因返回
onRejected(this.reason);
}
}
}
module.exports = MyPromise
往后的具体逻辑实现有时间再看,肝不动了,链接:深入分析 Promise 实现细节
参考:
https://juejin.cn/post/6945319439772434469#heading-15
https://juejin.cn/post/6953826402688827423#heading-3
https://juejin.cn/post/7069805387490263047
https://lzxjack.top/post?title=promise#heading-9
https://juejin.cn/post/6953826402688827423#heading-3