(SYNCHRONOUS VS ASYNCHRONOUS) LẬP TRÌNH ĐỒNG BỘ VÀ KHÔNG ĐỒNG BỘ
//!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');

Kết quả trả về:

Synchronous (Đồng bộ) là việc thực hiện các câu lệnh trong file từ trên xuống và trả về kết quả theo thứ tự từ trên xuống, tại một thời điểm chỉ xử lý một dòng lệnh.
Asynchronous (Bất đồng bộ) là việc xử lý các câu lệnh trả về kết quả không theo thứ tự từ trên xuống, tại một thời điểm có thể xử lý cùng lúc nhiều dòng lệnh bất đồng bộ khác nhau.
request (https://www.npmjs.com/package/request) để tải dữ liệu từ đường link sau về và hiển thị ra màn hình:
Sử dụng console.time và console.timeEnd để hiển thị ra thời gian tải link. Tìm hiểu về 2 hàm này tại: https://alligator.io/js/console-time-timeend/ hoặc google ‘console.time’
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):
/**
* 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);