Async Functionasync function aLog() {
console.log('Hello World !!!');
}
aLog();
//> babel-node index.js
//Hello World !!!
Arrow Function, sã thành:let aLog = async () => console.log('Hello World !!!');
aLog();
await chỉ được tồn tại trong Hàm Async FunctionAwait phải là một Async Functionawait + aPromise : Theo sau await phải là một Promise.Async Function thực hiện đến dòng lệnh có từ khóa await aPromise sẽ dừng lại vị trí await (không chạy các dòng lệnh tiếp theo ở dưới ), và chờ đợiaPromise đó thực hiện xong trả về kết quả; sau đó mới chạy các dòng lệnh tiếp theo.function helloLog() {
return Promise.resolve('Hello World');
}
// Basic Function
function basicLog() {
let str = helloLog().then((res) => res);
console.log('Basic: ', str);
}
// Async Function
async function syncLog() {
let str = await helloLog().then((res) => res);
console.log('Async Await: ', str);
}
syncLog();
basicLog();
// Basic: Promise { <pending> }
// Async Await: Hello World
basicLog() chạy sau syncLog(), nhưng hiển thị Log trước thể hiện xử lý Bất đồng bộ.str của Basic Function khi log ra vẫn chưa có giá trị (Promise { <pending> }) và vẫn đang ở trạng thái Pending.str của Async Function khi log ra đã thể hiện được giá trị (‘9’), nghĩa là sau khi await helloLog() chạy xong, mới chạy tiếp câu lệnh console.log('Async Await: ', str);function add(a, b) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (typeof a !== 'number' || typeof b !== 'number') {
return reject(new Error('Tham số phải là kiểu số!'));
}
return resolve(a + b);
}, 1000);
});
}
let phepCong = () => {
console.log('Basic');
let result = add(4, 5)
.then((res) => res)
.catch((err) => err);
console.log('Basic: ', result);
};
let syncPhepCong = async () => {
console.log('Async Await');
let result = await add(4, 5)
.then((res) => res)
.catch((err) => err);
console.log('Async Await: ', result);
};
phepCong();
syncPhepCong();
// Basic
// Basic: Promise { <pending> }
// Async Await
// Async Await: 9
Function thường thì Result vẫn chưa được gán giá trị(Promise { <pending> })thì vẫn chạy tiếp tục câu lệnh console.log( result);.Async Function thì được dừng tại await add(4, 5), sau khi Result nhận giá trị(9) thì mới chạy câu lệnh console.log( result);