khoa-pham-async-await

Làm quen với Async – Await


1. Async

async function aLog() {
  console.log('Hello World !!!');
}
aLog();

//> babel-node index.js
//Hello World !!!
let aLog = async () => console.log('Hello World !!!');
aLog();

2. Await

3. Các ví dụ về sự khác nhau giữa Hàm thường và Hàm Async Await

Ví dụ 1:

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

Ví dụ 2:

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