khoa-pham-async-await

Tìm hiểu Async – Await bất đồng bộ


1. Thực hiện bất đồng bộ Promise

function aLog(time, str) {
  return new Promise((resolve) => {
    setTimeout(() => {
      return resolve(str);
    }, time);
  });
}

function basicLog() {
  aLog(200, 'Dòng 1').then((res) => console.log('Basic: ', res));
  console.log('Basic');
  aLog(100, 'Dòng 2').then((res) => console.log('Basic: ', res));
}

basicLog();
// Basic
// Basic:  Dòng 2
// Basic:  Dòng 1
function aLog(time, str) {
  return new Promise((resolve) => {
    setTimeout(() => {
      return resolve(str);
    }, time);
  });
}

async function asynLog() {
  await aLog(200, 'Dòng 1').then((res) => console.log('Async: ', res));
  console.log('Async');
  await aLog(100, 'Dòng 2').then((res) => console.log('Async: ', res));
}

asynLog();
// Async:  Dòng 1
// Async
// Async:  Dòng 2

2. Nhận xét xử lý Async/Await