JavaScript 自學筆記34

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值