codersx-javascript-basic

SYNC. VS. ASYNC

(SYNCHRONOUS VS ASYNCHRONOUS) LẬP TRÌNH ĐỒNG BỘ VÀ KHÔNG ĐỒNG BỘ


1. Ví dụ:

//!Synchronous vs Asynchronous
const fs = require('fs');

//note: readFileSyn - readFile

//? Synchronous: readFileSyn
console.log('Begin Sync');
var data = fs.readFileSync('./detail/docs/test1.txt', 'utf-8');
console.log('Noi dung readFileSyn: ', data);
console.log('End Sync');
console.log('================================');
//? Asynchronous: readFile
console.log('Begin Async');
var data = fs.readFile('./detail/docs/test2.txt', 'utf-8', (err, data) => {
  if (err) {
    console.log(new Error(err));
  }
  console.log('Noi dung readFile Async: ', data);
});

console.log('End Async');

JAVASCRIPT VỚI HTML

Kết quả trả về:

Console


2. Nội dung:


3. Bài tập:

3.1 Bài tập 1:

3.2 Bài tập 2:

/**
 * Sử dụng module `axios` để tải dữ liệu và hiển thị ra màn hình lần lượt từng đường link (xong cái này rồi mới tới cái kia):
 * https://jsonplaceholder.typicode.com/todos/1
 * https://jsonplaceholder.typicode.com/todos/2
 */

const axios = require('axios');

function onDone(res) {
  return console.log(res.data);
}

function onError(err) {
  return console.error(err + '');
}

let getUser = (path) => {
  return new Promise((resolve, reject) => {
    return axios
      .get(path)
      .then((response) => resolve(response))
      .catch((error) => reject(error));
  });
};

getUser('https://jsonplaceholder.typicode.com/todos/1')
  .then((res) => {
    onDone(res);
    return getUser('https://jsonplaceholder.typicode.com/todos/33332');
  })
  .then((res) => {
    onDone(res);
    return getUser('https://jsonplaceholder.typicode.com/todos/3');
  })
  .then((res) => {
    onDone(res);
    return getUser('https://jsonplaceholder.typicode.com/todos/99994');
  })
  .then(onDone)
  .catch(onError);