一、理解JS中的错误(Error)和错误处理
1. 常见的内置错误:
- Error: 所有错误的父类型
- ReferenceError: 引用的变量不存在
- TypeError: 数据类型不正确的错误
- RangeError: 数据值不在其所允许的范围内
- SyntaxError: 语法错误
2. 错误处理
1. 捕获错误:try...catch
try {
let d;
console.log(d.xxx);
} catch (error) {
// error 是一个对象,里面有 message 和 stack 属性
console.log(error.message); // Cannot read properties of undefined (reading 'xxx')
console.log(error.stack); // TypeError: Cannot read properties of undefined (reading 'xxx')
}
console.log('aaac'); // 以上代码出错,此行代码依然可以执行
2. 抛出错误:throw new Error('参数')
// 抛出错误: throw error 【throw new Error(''),需要传递一个参数】
function something() {
if (Date.now() % 2 === 1) {
console.log('当前时间为奇数,可以执行任务');
} else { // 如果时间是偶数抛出异常,由调用者来处理
throw new Error('当前时间为偶数,不能正常执行任务');
}
}
// 由于该函数内部可能抛出异常,因此需要捕获处理异常
try {
something()
} catch (error) {
alert(error.message);
}
3. 错误对象
- message 属性:错误相关信息
- stack 属性:函数调用栈记录信息
二、Promise的基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Promise 的基本使用</title>
</head>
<body>
<script>
// 1. 创建一个新的 Promise 对象,参数 resolve reject 都是函数类型
const p = new Promise((resolve, reject) => { // 执行器函数,同步回调
console.log('执行 executor');
// 2. 执行异步任务
setTimeout(() => {
const time = +new Date(); // 如果当前时间是偶数,就代表成功 否则代表失败
// 3.1 如果成功,调用resolve(value)
if (time % 2 === 0) {
resolve('成功的数据, time = ' + time);
} else {
// 3.2 如果失败,调用reject(reason)
reject('失败的数据, time = ' + time);
}
}, 1000);
});
console.log('new Promise() 之后'); // 15行先于 28 行执行
setTimeout(function () {
p.then(
value => { // 接收得到成功的value数据 onResolved
console.log('成功的回调', value);
}, reason => { // 接收得到失败的reason数据 onRejected
console.warn('失败的回调', reason);
}
)
}, 3000)
</script>
</body>
</html>
三、对 Promise 的理解
1. 理解
1. Promise是JS中进行异步编程的新的解决方案【旧的异步编程,是纯回调形式】
2. 具体描述:
- 从语法上来说:Promise 是一个构造函数
- 从功能上来说:Promise 对象用来封装一个异步操作并可以获取其成功 / 失败的结果值
2. Promise 状态的改变
1. Promise 的状态总共有三种:pending [未知的、未确定的] 、resolved [成功的] 、rejected [失败的]
2. 状态改变(只有以下两种):
- pending 变为 resolved
- pending 变为 rejected
说明:一个Promise对象只能改变一次状态,无论是成功还是失败 都会有一个结果数据 成功的结果数据一般为 value,失败的结果数据一般称为 reason
四、为什么要用 Promise?
1. 指定回调函数的方式更加灵活
1. 旧的:必须在启动异步任务前指定
2.promise:启动异步任务 => 返回promise对象 => 给promise对象绑定回调函数.then(甚至可以在异步任务结束后指定/多个)
2.支持链式调用,可以解决回调地狱问题
1. 什么是回调地狱?
回调函数嵌套使用,外部回调函数异步执行的结果是嵌套的回调函数执行的条件
2. 回调地狱的缺点?
- 不便于阅读
- 不便于异常处理
3. 解决方案?
promise 链式调用。
promise 链式调用可以用来解决回调地狱问题,但是只是简单的改变格式,并没有彻底解决回调地狱的问题,要想真正解决回调地狱,要使用promise加上async和await实现。
4. 终极解决方案:
promise +async/await
五、使用 Promise
1. Promise 的几个API
1. Promise 构造函数: Promise(executor) { }
executor 函数[执行器函数]:同步执行 (resolve, reject) => { }
resolve 函数:内部定义成功时我们调用的函数 value => { }
reject 函数:内部定义失败时我们调用的函数 reason => { }
说明: executor 会在 Promise 内部立即同步回调,异步操作在执行器中执行
// 产生一个成功值为1的promise对象
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 100)
});
2. Promise.prototype.then 方法:(onResolved, onRejected) => { }
onResolved 函数:成功的回调函数 (value) => { }
onRejected 函数:失败的回调函数 (reason) => { }
说明:指定用于得到成功value的成功回调和用于得到失败reason的失败回调,返回一个 新的 promise 对象
// 产生一个成功值为1的promise对象
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 100)
});
p1.then(value => {
console.log(value);
});
3. Promise.prototype.catch 方法:(onRejected) => { }
onRejected 函数:失败的回调函数 (reason) => { }
说明:then() 的语法糖,相当于 then(undefined, onRejected)
let p = new Promise((resolve, reject) => {
reject('error');
});
p.catch(reason => {
console.log(reason);
});
4. Promise.resolve 方法:(value) => { }
value:成功的数据或 Promise 对象
说明:返回一个成功 / 失败的 promise 对象
- 如果传入的参数为 非Promise类型的对象, 则返回的结果为成功Promise对象
- 如果传入的参数为 Promise 对象, 则Promise对象的状态决定了 p2执行Resolve还是Rejected
let p1 = Promise.resolve(1) //返回成功的Promise
let p2 = Promise.resolve(new Promise((resolve,reject)=>{
//resolve(2)
reject(3) //错误的结果需要catch捕获否则报错
}))
console.log(p1);
console.log(p2);
p2.catch(reason =>{
console.log(reason);
})
5. Promise.reject 方法: (reason) => { }
reason:失败的原因
说明:返回一个失败的promise对象
- 如果传入的参数为 非Promise类型的对象, 则new Promise返回的结果永远为失败Promise对象
- 如果传入的参数为 Promise 对象, 则Promise对象的状态决定了 p执行Resolve还是Rejected
let p = Promise.reject(1)
let p2 = Promise.reject(new Promise((resolve, reject)=>{
resolve(2)
}))
console.log(p);
console.log(p2);
6. Promise.all 方法:(promises) => { }
promises:包含n个promise的数组
说明:返回一个新的promise,只有所有的promise都成功才成功,只要有一个失败了就直接失败
// Promise.all 方法:(promises) => { }
// promises:包含n个promise的数组
// 说明:返回一个新的promise,只有所有的promise都成功才成功,只要有一个失败了就直接失败
const pAll = Promise.all([p1, p2, p3]);
pAll.then(
value => {
console.log('pAll onResolved', value);
},
reason => {
console.log('pAll 失败, onRejected()', reason);
}
);
7. Promise.race 方法:(promises) => { }
promises:包含n个promise的数组
说明:返回一个新的 promise, 第一个完成的 promise 的结果状态就是最终的结果状态
// Promise.race 方法:(promises) => { }
// promises:包含n个promise的数组
// 说明:返回一个新的promise,第一个 完成的promise的结状态就 是最终的结果
// 只看第一个完成的,第一个成功 最终结果就是成功,否则失败【不一定是顺序排在第一个的,要看谁先完成】
const pRace = Promise.race([p1, p3, p2]); // 当p1迟,p3正常,返回的是p3返回的结果
pRace.then(
value => {
console.log('pRace 成功,onResolved()', value);
},
reason => {
console.log('pRace 失败,onRejected', reason);
}
)
2. Promise 的几个关键问题:
1. 如何改变 promise 的状态?
(1)resolve(value):如果当前是pending就会变为 resolved
(2)reject(reason):如果当前是pending就会变为 rejected
(3)抛出异常:如果当前是pending就会变为 rejected
const p = new Promise((resolve, reject) => {
// resolve(1); // promise 变为 resolved 的状态
// reject(2); // promise 变为 rejected 的状态
// throw new Error('出错啦!'); // 抛出异常,promise 变为 rejected 的状态,reason 就是被抛出来的 error
throw 3 // rejected 状态,此时 reason 为 3
});
2. 一个 promise 指定多个成功 / 失败的回调函数,都会调用吗?
当 promise 改变为对应状态时全都会调用。
const p = new Promise((resolve, reject) => {
// resolve(1); // promise 变为 resolved 的状态
// reject(2); // promise 变为 rejected 的状态
// throw new Error('出错啦!'); // 抛出异常,promise 变为 rejected 的状态,reason 就是被抛出来的 error
throw 3 // rejected 状态,此时 reason 为 3
});
// 多个 .then() ,都调用了
p.then(value => {
console.log('成功---', value);
},
reason => {
console.log('失败---', reason);
}
);
p.then(value => {
console.log('成功2---', value);
},
reason => {
console.log('失败2---', reason);
}
)
3. 改变 promise 状态和指定回调函数谁先执行?
1. 都有可能。正常情况下是先指定回调再改变状态,但也可以先改变状态再指定回调
// 常规:先指定回调,后改变状态
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1); // 后改变的状态(同时指定数据),异步执行回调函数
}, 1000);
}).then( // 先指定回调函数,保存当前指定的回调函数
value => { },
reason => { console.log('reason', reason); }
)
2. 如何先改状态再指定回调?
在执行器中直接调用 resolve( ) / reject( );延迟更长时间才调用 then( )
// 如何先该状态,后指定回调函数?【一般都是 先指定回调,后改变状态】
// 第一种:在执行器中直接调用 resolve() / reject()
new Promise((resolve, reject) => {
resolve(1); // 先改变状态(同时指定数据)
}).then( // 后指定回调函数,异步执行回调函数
value => { console.log('value2', value); },
reason => { console.log('reason2', reason); }
)
// 第二种:在 then 中使用定时器
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1); // 先改变状态(同时指定数据)
}, 1000);
});
// 设置定时器,只要比 resolve reject 晚,就可以
setTimeout(() => {
p.then( // 后指定回调函数,异步执行回调函数
value => { console.log('value3', value); },
reason => { console.log('reason3', reason); }
)
}, 2000)
3. 什么时候才能得到数据?
如果先指定的回调,那当状态发生改变时,回调函数就会调用 得到数据;如果先改变的状态,那当指定回调时,回调函数就会调用 得到数据
4. promise.then( ) 返回的新的promise的结果状态由什么决定?
1. 简单表达:由 then() 指定的回调函数执行的结果决定
2. 详细表达:
如果抛出异常,新 promise 变为 rejected ,reason 为抛出的异常
如果返回的是非 promise 的任意值,新 promise 变为 resolved , value 为返回的值
如果返回的是另一个新的 promise ,此 promise 的结果就会成为新的 promise 的结果
let p = new Promise((resolve, reject) => {
resolve('ok');
});
//执行 then 方法
let result = p.then(value => {
// console.log(value);
//1. 抛出错误
// throw '出错啦';
//2. 返回结果是非 Promise 类型的对象
// return 521;
//3. 返回结果是 Promise 对象
return new Promise((resolve, reject) => {
resolve('success');
//reject('error');
});
}, reason => {
console.warn(reason);
});
console.log(result);
5. promise 如何串联多个操作任务?
1. promise 的 then() 返回一个新的 promise,可以开启 then() 的链式调用
2. 通过 then 的链式调用串联多个 同步 / 异步任务
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('OK');
}, 1000);
});
p.then(value => {
return new Promise((resolve, reject) => {
resolve("success");
});
}).then(value => {
console.log(value);
}).then(value => {
//因为上个then没有返回任何东西所以输出undefined
console.log(value);
})
6. Promise 异常传透?
- 当使用 Promise 的 then 链式调用时, 可以在最后指定失败的回调
- 前面任何操作出了异常, 都会传到最后失败的回调中处理
new Promise((resolve, reject) => {
// resolve(1);
reject(1);
}).then(
value => {
console.log('onResolved1() ', value);
return 2;
},
reason => { throw reason }
).then(
value => {
console.log('onResolved2(): ', value);
return 3;
},
reason => { throw reason }
).then(
value => {
console.log('onResolved3(): ', value);
},
reason => Promise.reject(reason)
).catch(reason => {
console.log('onRejected1()', reason);
})
7. 中断 promise 链
- 当使用promise的then链式调用时,在中间中断,不再调用后面的回调函数
- 办法:在回调函数中返回一个pending状态的promise对象 return new Promise(( )=>{ })
new Promise((resolve, reject) => {
// resolve(1);
reject(1);
}).then(
value => {
console.log('onResolved1() ', value);
return 2;
},
reason => { throw reason }
).then(
value => {
console.log('onResolved2(): ', value);
return 3;
},
reason => { throw reason }
).then(
value => {
console.log('onResolved3(): ', value);
},
reason => Promise.reject(reason)
).catch(reason => {
console.log('onRejected1()', reason);
return new Promise(() => { }) // 返回pending状态的promise,后面不再执行,最终实现了 中断promise链
}).then(
value => {
console.log('onResolved3(): ', value);
},
reason => {
console.log('pnRejected2()', reason);
}
)
六、手写 Promise
// 自定义 promise 函数模块: IIFE
(function (window) {
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
/*
Promise 构造函数
executor 执行器函数(同步执行)
*/
function Promise(executor) {
// 将当前promise对象保存起来
const self = this;
self.status = PENDING; // 给promise对象指定status属性,初始值为pending
self.data = undefined; // 给promise对象指定一个用于存储结果数据的属性
self.callbacks = []; // 每个元素的结构: {onResolved() {}, onRejected() {}} , callbacks 数组里面都是对象
function resolve(value) {
// 如果当前状态不是 PENDING ,直接结束
if (self.status != PENDING) {
return;
}
// 将状态改为 RESOLVED
self.status = RESOLVED;
// 保存 value 数据
self.data = value;
// 如果有待执行的 callback 函数,立即 异步执行 回调函数 onResolved
if (self.callbacks.length > 0) {
setTimeout(() => { // 放入队列中执行所有成功的回调
self.callbacks.forEach(callbacksObj => {
callbacksObj.onResolved(value)
})
})
}
}
function reject(reason) {
// 如果当前状态不是 PENDING ,直接结束
if (self.status != PENDING) {
return;
}
// 将状态改为 REJECTED
self.status = REJECTED;
// 保存 reason 数据
self.data = reason;
// 如果有待执行的 callback 函数,立即 异步执行 回调函数 onRejected
if (self.callbacks.length > 0) {
setTimeout(() => { // 放入队列中执行所有失败的回调
self.callbacks.forEach(callbacksObj => {
callbacksObj.onRejected(reason);
})
})
}
}
// 立即同步执行 executor
try {
executor(resolve, reject);
} catch (error) { // 如果执行器抛出异常,promise对象变为rejected状态
reject(error);
}
}
/*
Promise 原型对象的 then() 方法
指定成功和失败的回调函数
返回一个新的 Promise 对象
返回的promise的结果由onResolved /onRejected执行的结果决定
*/
Promise.prototype.then = function (onResolved, onRejected) {
const self = this;
// 指定回调函数的默认值(必须是函数)
onResolved = typeof onResolved === 'function' ? onResolved : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
// 返回一个新的promise
return new Promise((resolve, reject) => {
/*
执行指定的回调函数
根据执行的结果改变return的promise的状态、数据
*/
function handle(callback) {
/*
返回的promise的结果由onResolved onRejected执行的结果决定
1. 抛出异常,返回的promise结果为失败,reason为抛出的异常
2. 返回非promise,返回的promise结果为成功,value 为返回的值
3. 如果onResolved返回的是promise,返回的promise的结果就是这个promise的结果,value或reason也相同
*/
try {
const result = callback(self.data);
if (result instanceof Promise) {
/*result.then(
value => resolve(value),
reason => reject(reason)
);*/
result.then(resolve, reject)
} else { // 返回非promise
resolve(result)
}
} catch (error) { // 抛出异常,返回的promise结果为失败,reason为抛出的异常
reject(error);
}
}
// 当前promise 的状态是 resolved
if (self.status === RESOLVED) {
// 立即异步执行成功的回调
setTimeout(() => {
handle(onResolved);
})
} else if (self.status === REJECTED) { // 当前promise 的状态是 rejected
// 立即异步执行失败的回调
setTimeout(() => {
handle(onRejected);
})
} else { // 当前promise 的状态是 pending
// 将成功和失败的回调函数保存到callbacks中缓存起来
self.callbacks.push({
onResolved(value) {
handle(onResolved);
},
onRejected(reason) {
handle(onRejected);
}
})
}
})
}
/*function fn(event) { }
div.onclick = function (event) {
fn(event)
}
div.onclick = fn*/
/*
Promise 原型对象的 catch()
指定失败的回调函数
返回一个新的 Promise 对象
*/
Promise.prototype.catch = function (onRejected) {
return this.then(undefined, onRejected);
}
/*
Promise 函数对象上的方法 resolve
返回指定结果value的成功的 Promise
*/
Promise.resolve = function (value) {
// 返回一个成功 或 失败的promise
return new Promise((resolve, reject) => {
// value 是promise
if (value instanceof Promise) { // 使用value的结果作为promise的结果
value.then(resolve, reject); // 此时参数value是Promise
} else {// value 不是promise => promise 成功,数据为 value
resolve(value);
}
})
}
/*
Promise 函数对象上的方法 reject
返回指定结果reason的失败的 Promise
*/
Promise.reject = function (reason) {
// 返回一个失败的promise
return new Promise((resolve, reject) => {
reject(reason)
})
}
/*
Promise 函数对象上的方法 all
返回一个 promise,只有当所有promise都成功时才成功,否则失败【只要有一个失败 就失败】
*/
Promise.all = function (promises) { // 数组里面的元素可能不是promise
const values = new Array(promises.length); // 用来保存所有成功value的数组
let resolvedCount = 0; // 用来保存成功promise的数量
return new Promise((resolve, reject) => {
// 遍历获取每个promise的结果
promises.forEach((p, index) => {
Promise.resolve(p).then(
value => { // p成功,将成功的value保存到values
// values.push(value)
resolvedCount++;
values[index] = value;
// 如果全部成功了,将return的promise改为成功
if (resolvedCount === promises.length) {
resolve(values);
}
},
reason => { // 只要有一个失败,return的promise失败
reject(reason)
}
)
})
})
}
/*
Promise 函数对象上的方法 race
返回一个 promise,其结果由第一个完成的promise来决定
*/
Promise.race = function (promises) {
// 返回一个 promise
return new Promise((resolve, reject) => {
// 遍历promises获取每个promise的结果
promises.forEach((p, index) => { // 因为元素p可能不是promise,可能是常量等类型,所以调用 Promise.resolve(p)
Promise.resolve(p).then(
value => { // 一旦有成功的,将return变为成功
resolve(value)
},
reason => { // 一旦有失败的,将return变为失败
reject(reason)
}
)
})
})
}
/*
返回一个promise对象,它在指定的时间后才确定结果
*/
Promise.resolveDelay = function (value, time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (value instanceof Promise) {
value.then(resolve, reject);
} else {
resolve(value)
}
}, time);
})
}
/*
返回一个promise对象,它在指定的时间后才失败
*/
Promise.rejectDelay = function (reason, time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(reason)
}, time);
})
}
// 向外暴露 Promise 函数
window.Promise = Promise;
})(window)
七、async 和 await
1. async 函数
- 函数的返回值为 promise 对象
- promise 对象的结果由 async 函数执行的返回值决定
async function fn1() {
// return 1;
// throw 2;
// return Promise.resolve(3);
// return Promise.reject(4);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(4)
}, 1000);
})
}
const result = fn1();
// console.log(result);
result.then(
value => {
console.log('onResolved() ', value);
},
reason => {
console.log('onRejected() ', reason);
}
)
2. await 表达式
- await 表达式的右侧一般为 promise 对象,但也可以是其他的值
- 如果表达式是 promise 对象,await 返回的是 promise 成功的值;如果 promise 失败了,会抛出异常,需要使用 try...catch 处理
- 如果表达式是其他值,直接将此值作为 await 的返回值
function fn2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// resolve(5)
reject(7)
}, 1000);
})
}
async function fn3() {
// const value = await fn2() // await 右侧表达式为promise,得到的结果就是promise成功的value
// const value = await 666 // await 右侧表达式不是promise,得到的结果就是这个值本身
try {
const value = await fn2()
console.log('value ', value);
} catch (error) {
console.log('得到失败的结果', error);
}
}
fn3()
注意:
- await 必须写在 async 函数中,但 async 函数中可以没有 await
- 如果 await 的promise 失败了,就会抛出异常,需要通过 try catch 来捕获处理