Promise状态
pending resolved rejected
调resolve函数会进入成功状态
调rejected函数或报错会进入失败状态
api
Promise.all Promise.race Promise.resolve Promise.reject是函数对象方法
.then .catch是实例对象方法
.then返回值
- 返回非promise的值,则下一个promise变为resolved值为.then返回值
- 抛出异常,则下一个promise变为rejected,值为抛出的异常
- 返回promise的值,此promise结果为新promise结果
- 如果是同步任务可以直接return,如果有异步任务则需要返回一个promise
Promise.resolve(2)
.then(x => {
console.log(x); // 输出2,也就是上面resolve参数值
return 'hello'; // 回调函数返回字符串类型
})
.then(x => {
console.log(x); // 输出hello,也就是上一个then回调函数返回值,表明上一个then的返回值就是下一个then的参数
// then函数回调函数中没有返回值
})
.then(x => {
// 前面的then的回调函数没有返回值所以这个x是undefined
console.log(x); // undefined
})
.then(() => {
return Promise.resolve('hello world');
})
.then(x => {
console.log(x); // hello world
});
async和await
async fn(){
// return 1(进入成功的回调)
// throw new Error(进入失败的回调)
// return Promise.resolve(1)(进入成功的回调)
}
const res=fn()
res.then(v=>{},err=>{})
async返回值是一个Promise,类似.then作用
await右边如果是Promise对象,得到的结果就是Promise成功的结果
await右边如果不是Promise对象,得到的就是它本身
如果想得到失败的结果值,则必须通过try catch实现