目录
常见的内置错误
1. ReferenceError 引用错误,引用不存在
console.log(a);
VM323:1 Uncaught ReferenceError: a is not defined
at <anonymous>:1:13
2. TypeError 数据类型错误
let b = null;
console.log(b.a);
VM1304:2 Uncaught TypeError: Cannot read property 'a' of null
at <anonymous>:2:15
3. RangeError 超出有效范围
function fn(){
fn();
}
fn();
VM1550:1 Uncaught RangeError: Maximum call stack size exceeded
4. SyntaxError 语法错误
let s = """";
VM1696:1 Uncaught SyntaxError: Unexpected string
Promise基础
Promise是什么?
- 从语法上说:是一个构造函数
- 从功能上说:Promise对象用来封装一个异步操作并可以获取其结果
Promise基本流程
Promise基本使用
const p = new Promise( function(resolve, reject) {...} /* 执行器为同步执行 */ );
p.then(//.then为同步执行
value => {
//成功的回调onRsolved为异步执行
},
reason => {
//失败的回调onRejected为异步执行
}
)
Promise.prototype.then(onRsolved, onRejected)
为什么使用Promise
1. 指定回调函数的方式更加灵活
- 纯回调:必须在启动异步任务前指定
- Promise:可以在异步任务有结果后指定
2. 支持链式调用,解决回调地狱
.then()返回的新Promise状态由什么决定?
- then如果抛出异常(throw Error(‘出错了’)),返回的新Promise状态为rejected
- then如果return非Promise的任意值,返回的新Promise状态为resolved
- then如果return一个Promise,由此Promise状态决定,如果此Promise状态为pending,则会阻断后续的链式回调
函数对象方法
- Promise.all()
- Promise.race()
- Promise.allSettled()
- Promise.reject()
- Promise.resolve()
函数原型方法
- Promise.prototype.catch(onRejected)
- Promise.prototype.then(onFulfilled, onRejected)
- Promise.prototype.finally(onFinally)
async函数 await表达式
基本概念
- async函数返回值为promise对象(与then()返回一样),此对象的结果有async函数执行的返回值决定
- await右侧的表达式一般为promise对象,如果是promise对象,await返回的是promise成功的值(不是promise),如果不是promise对象,直接将此值作为await的返回值
- await必须写在async函数中,如果await的promise失败了,就会抛出异常,需要try…catch来捕获