1. async / await 關鍵詞
ES2017引入了async / await關鍵詞,使異步代碼更具可讀性。
(1). 用法
- 在返回promise的函數前使用await關鍵詞。
如:let name = await getName();
- 注意await關鍵詞只能用在異步函數中。
如:// 通過學生學號獲取學生信息
function findStudent(studentID) {
return new Promise( (complete, failed) => {
setTimeout( () => {
complete( {
studentID,
name: 'Lulu'
} );
}, 2000 ); // 用setTimeout來模擬從數據庫調數據的延遲時間
});
};
// 通過學生姓名獲得學生課程
function getCourses(student) {
return new Promise( (complete, failed) => {
setTimeout( () => {
complete(['Math', 'React', 'JavaScript']);
},2000 );
} );
};
// 計算學生的縂課程數
function totalCourses(courses) {
return new Promise( (complete, failed) => {
setTimeout( () => {
complete(courses.length);
},2000 );
} );
};
// 在async函數中使用await關鍵詞
async function getResult() {
let student = await findStudent(19);
let courses = await getCourses(student);
let result = await totalCourses(courses);
console.log(`${student.name}'s total courses are ${result}.`);
}
getResult(); // Lulu's total courses are 3.
- 只要在函數前加上async關鍵詞,此函數即爲異步函數。
如:async function getResult(){ // ... };
或, let result = async function () { //... };
又或,let result = async () => //...;
(2). 異常處理
- 可以使用try...catch處理異常
如:async function getResult() {
try{
let student = await findStudent(19);
let courses = await getCourses(student);
let result = await totalCourses(courses);
console.log(`${student.name}'s total courses are ${result}.`);
} catch (e) {
console.log(e);
}
}