目錄
常見的內置錯誤
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來捕獲