Chuyển tới nội dung chính

Javascript - Cheatsheet

Tổng hợp Cheatsheet Javascript - Tóm tắt JavaScript với các khái niệm, hàm, phương thức... quan trọng nhất.

cửa hàng
roadmaps
cheatsheet
tài liệu phỏng vấn

🔖 Gợi ý từ Admin

📝 Tài liệu phỏng vấn kiến thức lập trình: Xem tại đây!!!

📌 Tìm hiểu về thuật toán: Xem tại đây!!!

📌 Roadmaps - Lộ trình trở thành một lập trình viên: Xem tại đây!!!

⚡️ Cheatsheet các ngôn ngữ lập trình: Xem tại đây!!!

⚡️ Handbook lập trình: Xem tại đây!!!

I. Tổng hợp Cheatsheet Javascript

1. Cơ bản

⚡️ Console

Console
// => Hello world!
console.log('Hello world!');

// => Hello thanhnamnguyen.dev
console.warn('hello %s', 'thanhnamnguyen.dev');

// In ra lỗi "Oops!"
console.error(new Error('Oops!'));

⚡️ Số (Numbers)

Numbers
let amount = 6;
let price = 4.99;

⚡️ Biến (Variables)

Variables
let x = null;
let name = 'Tammy';
const found = false;

// => Tammy, false, null
console.log(name, found, x);

var a;
console.log(a); // => undefined

⚡️ Chuỗi (Strings)

Strings
let single = 'Hello, thanhnamnguyen.dev';

// => 21
console.log(single.length);

⚡️ Toán tử số học (Arithmetic Operators)

Arithmetic Operators
5 + 5 = 10     // Cộng (Addition)
10 - 5 = 5 // Trừ (Subtraction)
5 * 10 = 50 // Nhân (Multiplication)
10 / 5 = 2 // Chia (Division)
10 % 5 = 0 // Chia lấy dư (Modulo)

⚡️ Bình luận (Comments)

Comments
// Comment 1 dòng

/*
Comment
nhiều dòng
*/

⚡️ Toán tử gán (Assignment Operators)

Assignment Operators
let number = 100;

number = number + 10;
number += 10;

console.log(number);
// => 120

⚡️ Chuỗi nội suy (String Interpolation)

String Interpolation
let age = 7;

// Nối chuỗi (String concatenation)
'Tommy is ' + age + ' years old.';

// Chuỗi nội suy (String interpolation)
`Tommy is ${age} years old.`;

⚡️ Từ khoá let

let
let count;
console.log(count); // => undefined
count = 10;
console.log(count); // => 10

⚡️ Từ khoá const

const
const numberOfColumns = 4;

// TypeError: Assignment to constant...
numberOfColumns = 8;

2. JavaScript Conditionals (câu lệnh điều kiện)

⚡️ Câu điều kiện if (if Statement)

const isMailSent = true;

if (isMailSent) {
console.log('Mail sent to recipient');
}

⚡️ Toán tử 3 ngôi (Ternary Operator)

var x = 1;

// => true
result = x == 1 ? true : false;

⚡️ Câu lệnh if else

if else
const size = 10;

if (size > 100) {
console.log('Big');
} else if (size > 20) {
console.log('Medium');
} else if (size > 4) {
console.log('Small');
} else {
console.log('Tiny');
}
// Print: Small

⚡️ Câu lệnh switch (switch Statement)

switch Statement
const food = 'salad';

switch (food) {
case 'oyster':
console.log('The taste of the sea');
break;
case 'pizza':
console.log('A delicious pie');
break;
default:
console.log('Enjoy your meal');
}

⚡️ =====: == chỉ kiểm tra giá trị, === kiểm tra cả giá trị lẫn kiểu dữ liệu.

0 == false; // true
0 === false; // false, different type
1 == '1'; // true, automatic type conversion
1 === '1'; // false, different type
null == undefined; // true
null === undefined; // false
'0' == false; // true
'0' === false; // false

⚡️ Toán tử (Operators)

Operators
true || false; // true
10 > 5 || 10 > 20; // true
false || false; // false
10 > 100 || 10 > 20; // false

// Toán tử logic &&
true && true; // true
1 > 2 && 2 > 1; // false
true && false; // false
4 === 4 && 3 > 1; // true

// Toán tử so sánh
1 > 3; // false
3 > 1; // true
250 >= 250; // true
1 === 1; // true
1 === 2; // false
1 === '1'; // false

// Toán tử logic !
let lateToWork = true;
let oppositeValue = !lateToWork;

// => false
console.log(oppositeValue);

// Toán tử hợp nhất Nullish ??
null ?? 'I win'; // 'I win'
undefined ?? 'Me too'; // 'Me too'

false ?? 'I lose'; // false
0 ?? 'I lose again'; // 0
'' ?? 'Damn it'; // ''

3. JavaScript Functions (hàm)

⚡️ Functions (Hàm)

Functions
// Định nghĩa hàm:
function sum(num1, num2) {
return num1 + num2;
}

// Gọi hàm:
sum(3, 6); // 9

⚡️ Anonymous Functions (hàm ẩn danh): là các hàm không có tên được định nghĩa trực tiếp trong một biểu thức hoặc biểu thức gán giá trị cho một biến.

Anonymous Functions
// Dạng cơ bản
const anonymousFunction = function (parameters) {
// Các câu lệnh trong hàm
};

// Hàm không có tham số
const greet = function () {
console.log('Hello!');
};

// Hàm có tham số
const add = function (a, b) {
return a + b;
};

Anonymous functions thường được sử dụng khi chúng ta chỉ cần sử dụng hàm một lần và không cần phải tái sử dụng lại nó.

⚡️ Arrow Functions (ES6)

Arrow Functions (ES6)
// Với 2 đối số
const sum = (param1, param2) => {
return param1 + param2;
};
console.log(sum(2, 5)); // => 7

// Không có đối số
const printHello = () => {
console.log('hello');
};
printHello(); // => hello

// Chỉ 1 đối số
const checkWeight = (weight) => {
console.log(`Weight : ${weight}`);
};
checkWeight(25); // => Weight : 25

// arrow functions ngắn gọn
const multiply = (a, b) => a * b;
// => 60
console.log(multiply(2, 30));

⚡️ Từ khoá return

return keyword
// Có return
function sum(num1, num2) {
return num1 + num2;
}

// Hàm không có kết quả trả về
function sum(num1, num2) {
num1 + num2;
}

⚡️ Gọi hàm (Calling Functions)

Calling Functions
// Định nghĩa hàm
function sum(num1, num2) {
return num1 + num2;
}

// Gọi hàm
sum(2, 4); // 6

⚡️ Function Expressions

Function Expressions
const dog = function () {
return 'Woof!';
};

⚡️ Function Parameters

Function Parameters
// Tham số truyền vào là name
function sayHello(name) {
return `Hello, ${name}!`;
}

⚡️ Function Declaration

Function Declaration
function add(num1, num2) {
return num1 + num2;
}

4. JavaScript Scope (phạm vi)

⚡️ Scope

Scope
function myFunction() {
var pizzaName = 'Margarita';
// Code ở đây có thể sử dụng pizzaName
}

// Code ở đây không thể sử dụng pizzaName

⚡️ Block Scoped Variables

Block Scoped Variables
const isLoggedIn = true;

if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}

// Uncaught ReferenceError...
console.log(statusMessage);

⚡️ Global Variables

Global Variables
// Variable được khai báo toàn cục
const color = 'blue';

function printColor() {
console.log(color);
}

printColor(); // => blue

⚡️ let vs var: 1 nằm trong phạm vi khối function gần nhất và 1 nằm trong phạm vi khối enclosing gần nhất.

for (let i = 0; i < 3; i++) {
// Đây là phạm vi tối đa của 'let'
// i có thể truy cập ✔️
}
// i không có thể truy cập ❌

for (var i = 0; i < 3; i++) {
// i có thể truy cập ✔️
}
// i có thể truy cập ✔️

⚡️ Loops with closures

Loops with closures
// In ra `3` 3 lần. Không như ý muốn ban đầu.
for (var i = 0; i < 3; i++) {
setTimeout((_) => console.log(i), 10);
}

// In ra 0, 1 và 2, đúng như mong đợi.
for (let j = 0; j < 3; j++) {
setTimeout((_) => console.log(j), 10);
}

Biến có bản sao riêng của nó khi sử dụng let, và biến có bản sao được chia sẻ khi sử dụng var.

5. JavaScript Arrays (Mảng)

⚡️ Arrays

Arrays
const fruits = ['apple', 'orange', 'banana'];

// Các loại dữ liệu khác nhau
const data = [1, 'chicken', false];

⚡️ Thuộc tính .length

Property .length
const numbers = [1, 2, 3, 4];

numbers.length; // 4

⚡️ Index

Index
// Truy cập các phần tử của mảng
const myArray = [100, 200, 300];

console.log(myArray[0]); // 100
console.log(myArray[1]); // 200

⚡️ Mutable chart

addremovestartend
push
pop
unshift
shift

⚡️ Phương thức .push()

Method .push()
// Thêm 1 phần tử
const cart = ['apple', 'orange'];
cart.push('pear');

// Thêm nhiều phần tử
const numbers = [1, 2];
numbers.push(3, 4, 5);

// Thêm phần tử vào cuối và trả về độ dài của mảng.

⚡️ Phương thức .pop()

Method .pop()
const fruits = ['apple', 'orange', 'banana'];

const fruit = fruits.pop(); // 'banana'
console.log(fruits); // ["apple", "orange"]
// Xoá phần tử ở cuối và trả về phần tử đã được xoá.

⚡️ Phương thức .shift()

Method .shift()
let cats = ['Bob', 'Willy', 'Mini'];

cats.shift(); // ['Willy', 'Mini']
// Xoá phần tử đẩu và trả về phần tử đã được xoá.

⚡️ Phương thức .unshift()

Method .unshift()
let cats = ['Bob'];

// => ['Willy', 'Bob']
cats.unshift('Willy');

// => ['Puff', 'George', 'Willy', 'Bob']
cats.unshift('Puff', 'George');
// Thêm phần tử vào đầu và trả về độ dài của mảng mới.

⚡️ Phương thức .concat()

Method .concat()
const numbers = [3, 2, 1];
const newFirstNumber = (4)[newFirstNumber] // => [ 4, 3, 2, 1 ]
.concat(numbers);

// => [ 3, 2, 1, 4 ]
numbers.concat(newFirstNumber);
// Tránh ảnh hưởng đến mảng cũ, bạn có thể sử dụng concat()

6. JavaScript Loops (vòng lặp)

⚡️ Vòng lặp while

While Loop
while (condition) {
// code block to be executed
}

let i = 0;
while (i < 5) {
console.log(i);
i++;
}

⚡️ Đảo ngược vòng lặp

Reverse Loop
const fruits = ['apple', 'orange', 'banana'];

for (let i = fruits.length - 1; i >= 0; i--) {
console.log(`${i}. ${fruits[i]}`);
}

// => 2. banana
// => 1. orange
// => 0. apple

⚡️ Câu lệnh do while

Do…While Statement
x = 0;
i = 0;

do {
x = x + i;
console.log(x);
i++;
} while (i < 5);
// => 0 1 3 6 10

⚡️ Vòng lặp for

For Loop
for (let i = 0; i < 4; i += 1) {
console.log(i);
}

// => 0, 1, 2, 3

⚡️ Vòng lặp qua mảng

Looping Through Arrays
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}

⚡️ Break

Break
for (let i = 0; i < 99; i += 1) {
if (i > 5) {
break;
}
console.log(i);
}
// => 0 1 2 3 4 5

⚡️ Continue

Continue
for (i = 0; i < 10; i++) {
if (i === 3) {
continue;
}
text += 'The number is ' + i + '<br>';
}

⚡️ Vòng lặp lồng nhau

Nested loop
for (let i = 0; i < 2; i += 1) {
for (let j = 0; j < 3; j += 1) {
console.log(`${i}-${j}`);
}
}

⚡️ Vòng lặp for...in: là một cấu trúc lặp trong JavaScript được sử dụng để lặp qua các thuộc tính có thể liệt kê của một đối tượng.

for...in loop
const fruits = ['apple', 'orange', 'banana'];

for (let index in fruits) {
console.log(index);
}
// => 0
// => 1
// => 2

⚡️ Vòng lặp for...of: là một cấu trúc lặp trong JavaScript được sử dụng để lặp qua các phần tử của một iterable object như mảng, chuỗi, hoặc bất kỳ đối tượng nào có khả năng lặp qua.

for...of loop
const fruits = ['apple', 'orange', 'banana'];

for (let fruit of fruits) {
console.log(fruit);
}
// => apple
// => orange
// => banana

7. JavaScript Iterators

⚡️ Hàm được gán cho biến: hàm có thể được gán cho biến, được truyền như tham số cho các hàm khác, hoặc được trả về từ một hàm. Việc gán hàm cho biến rất phổ biến và linh hoạt.

Functions Assigned to Variables
// Định nghĩa hàm
function sayHello(name) {
console.log(`Hello, ${name}!`);
}

// Gán hàm cho biến
const greet = sayHello;

// Gọi hàm thông qua biến
greet('Alice'); // In ra: Hello, Alice!

⚡️ Hàm Callback: là một hàm được truyền vào một hàm khác như một tham số và được gọi bởi hàm đó trong một thời điểm xác định. Trong ngữ cảnh của JavaScript, hàm callback thường được sử dụng trong các hàm bất đồng bộ (asynchronous) như các phương thức của Promise, setTimeout, setInterval, và các sự kiện như xử lý sự kiện trong trình duyệt.

Một hàm callback có thể được định nghĩa dưới dạng hàm thông thường hoặc dưới dạng hàm nặc danh (anonymous function).

Callback Functions
// Hàm callback được định nghĩa thông thường
function myCallback(result) {
console.log(`Callback called with result: ${result}`);
}

// Hàm nhận một hàm callback làm tham số
function performTask(callback) {
const result = 'Task completed';
callback(result);
}

// Gọi hàm và truyền hàm callback vào đó
performTask(myCallback);

⚡️ Phương thức .reduce(): là một phương thức của mảng trong JavaScript, được sử dụng để thực hiện một hàm callback trên mỗi phần tử của mảng để tính toán một giá trị duy nhất. Giá trị này được tích lũy qua các lần gọi của hàm callback và cuối cùng trả về kết quả.

const result = array.reduce(callback(accumulator, currentValue, index, array), initialValue);

Trong đó:

  • array: Mảng gốc mà bạn muốn thực hiện .reduce() lên.
  • callback: Hàm callback được gọi cho mỗi phần tử của mảng, nhận vào hai tham số là accumulator (giá trị tích lũy) và currentValue (giá trị của phần tử hiện tại).
  • accumulator: Giá trị tích lũy từ các lần gọi trước đó của hàm callback.
  • currentValue: Giá trị của phần tử hiện tại.
  • index: Chỉ số của phần tử hiện tại.
  • array: Mảng đang được thực hiện .reduce().
  • initialValue (tùy chọn): Giá trị khởi tạo cho accumulator. Nếu không được cung cấp, phần tử đầu tiên của mảng sẽ được sử dụng làm giá trị khởi tạo.
Array Method .reduce()
const numbers = [1, 2, 3, 4, 5];

// Tính tổng của mảng
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15

⚡️ Phương thức .map(): là một phương thức của mảng trong JavaScript, được sử dụng để tạo ra một mảng mới bằng cách gọi một hàm callback cho mỗi phần tử của mảng. Kết quả trả về của .map() là một mảng mới với các giá trị được thay đổi dựa trên hàm callback.

const newArray = array.map(callback(currentValue, index, array), thisArg);

Trong đó:

  • array: Mảng gốc mà bạn muốn thực hiện .map() lên.
  • callback: Hàm callback được gọi cho mỗi phần tử của mảng.
  • currentValue: Giá trị của phần tử hiện tại.
  • index: Chỉ số của phần tử hiện tại.
  • array: Mảng đang được thực hiện .map().
  • thisArg (tùy chọn): Giá trị được sử dụng làm giá trị this trong hàm callback.
Array Method .map()
const numbers = [1, 2, 3, 4, 5];

// Tạo một mảng mới chứa bình phương của mỗi số
const squaredNumbers = numbers.map((number) => number ** 2);

console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

⚡️ Phương thức .forEach(): là một phương thức của mảng trong JavaScript, được sử dụng để lặp qua từng phần tử của mảng và thực hiện một hàm callback cho mỗi phần tử đó.

array.forEach(callback(currentValue, index, array), thisArg);

Trong đó:

  • array: Mảng mà bạn muốn lặp qua.
  • callback: Hàm callback được gọi cho mỗi phần tử của mảng.
  • currentValue: Giá trị của phần tử hiện tại.
  • index: Chỉ số của phần tử hiện tại.
  • array: Mảng đang được lặp qua.
  • thisArg (tùy chọn): Giá trị được sử dụng làm giá trị this trong hàm callback.
Array Method .forEach()
const fruits = ['Apple', 'Banana', 'Orange'];

fruits.forEach((fruit, index) => {
console.log(`Fruit at index ${index}: ${fruit}`);
});

// Output
// Fruit at index 0: Apple
// Fruit at index 1: Banana
// Fruit at index 2: Orange

⚡️ Phương thức .filter(): là một phương thức của mảng trong JavaScript, được sử dụng để tạo một mảng mới chứa các phần tử của mảng gốc thoả mãn một điều kiện xác định. Nó không thay đổi mảng gốc, mà thay vào đó tạo ra một mảng mới chứa các phần tử được lọc.

array.filter(callback(element, index, array), thisArg);

Trong đó:

  • array: Mảng gốc cần được lọc.
  • callback: Hàm callback được gọi cho mỗi phần tử của mảng. Nếu hàm này trả về true, phần tử đó sẽ được bao gồm trong mảng mới; ngược lại, nếu trả về false, phần tử đó sẽ bị loại bỏ.
  • element: Giá trị của phần tử hiện tại.
  • index: Chỉ số của phần tử hiện tại.
  • array: Mảng gốc đang được lọc.
  • thisArg (tùy chọn): Giá trị được sử dụng làm giá trị this trong hàm callback.
Array Method .filter()
const numbers = [1, 2, 3, 4, 5, 6];

// Lọc các số chẵn
const evenNumbers = numbers.filter((number) => number % 2 === 0);

console.log(evenNumbers); // Output: [2, 4, 6]

8. JavaScript Objects

⚡️ Truy cập vào thuộc tính

Accessing Properties
const apple = {
color: 'Green',
price: { bulk: '$3/kg', smallQty: '$4/kg' },
};
console.log(apple.color); // => Green
console.log(apple.price.bulk); // => $3/kg

⚡️ Đặt tên thuộc tính

Naming Properties
// Ví dụ về key không hợp lệ
const trainSchedule = {
// Không hợp lệ bởi vì chứa khoảng trắng.
platform num: 10,
// Biểu thức không thể là key.
40 - 10 + 2: 30,
// Dấu + không hợp lệ, trừ khi để trong ngoặc kép ""
+compartment: 'C'
}

⚡️ Thuộc tính không tồn tại

Non-existent properties
const classElection = {
date: 'January 12',
};

console.log(classElection.place); // undefined

⚡️ Cú pháp viết tắt

Assignment shorthand syntax
const person = {
name: 'Tom',
age: '22',
};
const { name, age } = person;
console.log(name); // 'Tom'
console.log(age); // '22'

⚡️ Có thể thay đổi giá trị

Mutable
const student = {
name: 'Sheldon',
score: 100,
grade: 'A',
};

console.log(student);
// { name: 'Sheldon', score: 100, grade: 'A' }

delete student.score;
student.grade = 'F';
console.log(student);
// { name: 'Sheldon', grade: 'F' }

student = {};
// TypeError: Assignment to constant variable.

⚡️ Toán tử delete

Delete operator
const person = {
firstName: 'Matilda',
age: 27,
hobby: 'knitting',
goal: 'learning JavaScript',
};

delete person.hobby; // hoặc delete person[hobby];

console.log(person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/

⚡️ Đối tượng làm 1 đối số

Objects as arguments
const origNum = 8;
const origObj = { color: 'blue' };

const changeItUp = (num, obj) => {
num = 7;
obj.color = 'red';
};

changeItUp(origNum, origObj);

// Sẽ xuất ra 8 vì số nguyên được truyền theo giá trị.
console.log(origNum);

// Sẽ xuất ra 'red' vì các đối tượng được truyền theo tham chiếu và do đó có thể thay đổi được.
console.log(origObj.color);

⚡️ Tạo đối tượng

Shorthand object creation
const activity = 'Surfing';
const beach = { activity };
console.log(beach); // { activity: 'Surfing' }

⚡️ Từ khoá this

this Keyword
const cat = {
name: 'Pipey',
age: 8,
whatName() {
return this.name;
},
};
console.log(cat.whatName()); // => Pipey

⚡️ Hàm Factory

Factory functions
// A factory function chấp nhận các tham số 'name',
// 'age', và 'breed' để trả về 1 đối tượng tuỳ chỉnh
const dogFactory = (name, age, breed) => {
return {
name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');
},
};
};

⚡️ Phương thức

Methods
const engine = {
// phương thức với 1 đối số
start(adverb) {
console.log(`The engine starts up ${adverb}...`);
},
// biểu thức arrow func ẩn danh không có đối số
sputter: () => {
console.log('The engine sputters...');
},
};

engine.start('noisily');
engine.sputter();

⚡️ Getters và setters

Getters and setters
const myCat = {
_name: 'Dottie',
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
},
};

// Tham chiếu gọi getter
console.log(myCat.name);

// Gán giá trị gọi setter
myCat.name = 'Yankee';

9. JavaScript Classes

⚡️ Phương thức tĩnh (Static Methods)

Static Methods
class Dog {
constructor(name) {
this._name = name;
}

introduce() {
console.log('This is ' + this._name + ' !');
}

// Phương thức tĩnh
static bark() {
console.log('Woof!');
}
}

const myDog = new Dog('Buster');
myDog.introduce();

// Gọi phương thức tĩnh
Dog.bark();

⚡️ Lớp (Class)

Class
class Song {
constructor() {
this.title;
this.author;
}

play() {
console.log('Song playing!');
}
}

const mySong = new Song();
mySong.play();

⚡️ Lớp khởi tạo (Class Constructor)

Class Constructor
class Song {
constructor(title, artist) {
this.title = title;
this.artist = artist;
}
}

const mySong = new Song('Bohemian Rhapsody', 'Queen');
console.log(mySong.title);

⚡️ Phương thức lớp (Class Methods)

Class Methods
class Song {
play() {
console.log('Playing!');
}

stop() {
console.log('Stopping!');
}
}

⚡️ Kế thừa (extends)

extends
// Lớp cha
class Media {
constructor(info) {
this.publishDate = info.publishDate;
this.name = info.name;
}
}

// Lớp con
class Song extends Media {
constructor(songData) {
super(songData);
this.artist = songData.artist;
}
}

const mySong = new Song({
artist: 'Queen',
name: 'Bohemian Rhapsody',
publishDate: 1975,
});

10. JavaScript Modules

⚡️ Export

Export
// myMath.js

// Default export
export default function add(x, y) {
return x + y;
}

// Normal export
export function subtract(x, y) {
return x - y;
}

// Multiple exports
function multiply(x, y) {
return x * y;
}
function duplicate(x) {
return x * 2;
}
export { multiply, duplicate };

⚡️ Import

Import
// main.js
import add, { subtract, multiply, duplicate } from './myMath.js';

console.log(add(6, 2)); // 8
console.log(subtract(6, 2)) // 4
console.log(multiply(6, 2)); // 12
console.log(duplicate(5)) // 10

// index.html
<script type="module" src="main.js"></script>

⚡️ Export Module

Export Module
// myMath.js

function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
}
function duplicate(x) {
return x * 2;
}

// Multiple exports in node.js
module.exports = {
add,
subtract,
multiply,
duplicate,
};

⚡️ Require Module

Require Module
// main.js
const myMath = require('./myMath.js');

console.log(myMath.add(6, 2)); // 8
console.log(myMath.subtract(6, 2)); // 4
console.log(myMath.multiply(6, 2)); // 12
console.log(myMath.duplicate(5)); // 10

11. JavaScript Promises

⚡️ Trạng thái Promise

  • Pending (Đang chờ xử lý): Trạng thái ban đầu của một Promise. Nếu Promise đang trong trạng thái pending, có nghĩa là chưa được giải quyết (resolved) hoặc từ chối (rejected).
  • Fulfilled (Đã được giải quyết): Khi một Promise kết thúc một công việc một cách thành công, nó chuyển sang trạng thái fulfilled. Trong trạng thái này, Promise có thể mang theo một giá trị được giải quyết (resolved value).
  • Rejected (Đã bị từ chối): Nếu một Promise gặp phải lỗi hoặc bất kỳ vấn đề nào khi thực hiện công việc, nó sẽ chuyển sang trạng thái rejected. Trong trạng thái này, Promise có thể mang theo một lý do (reason) cho việc từ chối.
Promise states
const myPromise = new Promise((resolve, reject) => {
// Thực hiện công việc nào đó
const success = true;

if (success) {
resolve('Thành công!'); // Chuyển sang trạng thái fulfilled
} else {
reject('Có lỗi!'); // Chuyển sang trạng thái rejected
}
});

myPromise
.then((result) => {
console.log('Giải quyết:', result);
})
.catch((error) => {
console.error('Từ chối:', error);
});

⚡️ Executor function

Executor function
const executorFn = (resolve, reject) => {
resolve('Resolved!');
};

const promise = new Promise(executorFn);

⚡️ setTimeout()

setTimeout()
const loginAlert = () => {
console.log('Login');
};

setTimeout(loginAlert, 6000);

⚡️ Phương thức .then(): là một phương thức của đối tượng Promise trong JavaScript, được sử dụng để đính kèm các hành động xử lý cho kết quả thành công (resolve) của một Promise. Khi một Promise được giải quyết (resolved), .then() sẽ được gọi và thực hiện hàm callback được cung cấp.

.then() method
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Result');
}, 200);
});

promise.then(
(res) => {
console.log(res);
},
(err) => {
console.error(err);
},
);

⚡️ Phương thức .catch(): là một phương thức của đối tượng Promise trong JavaScript, được sử dụng để xử lý lỗi (rejections) từ một Promise. Nếu một Promise bị từ chối (rejected) và không có xử lý nào được thực hiện bằng .then(), thì .catch() sẽ được gọi để xử lý lỗi đó.

.catch() method
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(Error('Promise Rejected Unconditionally.'));
}, 1000);
});

promise.then((res) => {
console.log(value);
});

promise.catch((err) => {
console.error(err);
});

⚡️ Promise.all(): là một phương thức trong JavaScript Promise API, được sử dụng để chờ đợi cho tất cả các Promise trong một mảng Promise được giải quyết (resolved) hoặc từ chối (rejected). Nó trả về một Promise mới mà khi tất cả các Promise trong mảng đã được giải quyết, Promise mới đó sẽ được giải quyết với một mảng chứa kết quả của từng Promise theo thứ tự ban đầu.

Promise.all()
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 300);
});

const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 200);
});

Promise.all([promise1, promise2]).then((res) => {
console.log(res[0]);
console.log(res[1]);
});

⚡️ Tránh lồng Promise và .then()

Avoiding nested Promise and .then()
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('*');
}, 1000);
});

const twoStars = (star) => {
return star + star;
};

const oneDot = (star) => {
return star + '.';
};

const print = (val) => {
console.log(val);
};

// Xâu chuỗi tất cả chúng lại với nhau
promise.then(twoStars).then(oneDot).then(print);

⚡️ Tạo 1 promise

Creating
const executorFn = (resolve, reject) => {
console.log('The executor function of the promise!');
};

const promise = new Promise(executorFn);

⚡️ Xâu chuỗi .then()

Chaining multiple .then()
// Tạo một Promise đơn giản trả về một giá trị sau một khoảng thời gian
function createPromise(value, delay) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Resolved with value: ${value}`);
resolve(value);
}, delay);
});
}

// Sử dụng chaining để thực hiện các Promise theo thứ tự
createPromise(1, 1000)
.then((result1) => {
// Xử lý kết quả của Promise thứ nhất và trả về một giá trị mới
console.log(`Result from the first promise: ${result1}`);
return createPromise(2, 1500);
})
.then((result2) => {
// Xử lý kết quả của Promise thứ hai và trả về một giá trị mới
console.log(`Result from the second promise: ${result2}`);
return createPromise(3, 2000);
})
.then((result3) => {
// Xử lý kết quả của Promise thứ ba
console.log(`Result from the third promise: ${result3}`);
})
.catch((error) => {
// Xử lý lỗi nếu có bất kỳ Promise nào bị reject
console.error(`Error: ${error}`);
});

⚡️ Làm giả 1 http Request với Promise

Fake http Request with Promise
const mock = (success, timeout = 1000) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (success) {
resolve({ status: 200, data: {} });
} else {
reject({ message: 'Error' });
}
}, timeout);
});
};
const someEvent = async () => {
try {
await mock(true, 1000);
} catch (e) {
console.log(e.message);
}
};

12. JavaScript Async-Await

⚡️ Asynchronous

Asynchronous
function helloWorld() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}

const msg = async function () {
const msg = await helloWorld();
console.log('Message:', msg);
};

const msg1 = async () => {
const msg = await helloWorld();
console.log('Message:', msg);
};

msg(); // Message: Hello World! <-- sau 2s
msg1(); // Message: Hello World! <-- sau 2s

⚡️ Resolving Promises

Resolving Promises
let pro1 = Promise.resolve(5);
let pro2 = 44;
let pro3 = new Promise(function (resolve, reject) {
setTimeout(resolve, 100, 'foo');
});

Promise.all([pro1, pro2, pro3]).then(function (values) {
console.log(values);
});
// expected => Array [5, 44, "foo"]

⚡️ Async Await Promises

Async Await Promises
function helloWorld() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}

async function msg() {
const msg = await helloWorld();
console.log('Message:', msg);
}

msg(); // Message: Hello World! <-- sau 2s

⚡️ Error Handling: bạn có thể sử dụng khối try/catch để xử lý lỗi trong các hàm async/await.

Error Handling
let json = '{ "age": 30 }'; // dữ liệu không đầy đủ

try {
let user = JSON.parse(json); // <-- không có lỗi
console.log(user.name); // không có name
} catch (e) {
console.error('Invalid JSON data!');
}

⚡️ Async await operator: là cặp từ khóa trong JavaScript được sử dụng để làm cho việc xử lý mã không đồng bộ (asynchronous code) trở nên dễ đọc và dễ hiểu hơn.

  • async:
    • Bạn có thể định nghĩa một hàm không đồng bộ (asynchronous) bằng cách thêm từ khóa async trước khai báo hàm.
    • Hàm async luôn trả về một Promise.
  • await:
    • Từ khóa await được sử dụng bên trong một hàm async để tạm dừng thực thi của hàm cho đến khi một Promise được giải quyết.
    • Nó chỉ có thể được sử dụng bên trong hàm async.
Async await operator
function helloWorld() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}

async function msg() {
const msg = await helloWorld();
console.log('Message:', msg);
}

msg(); // Message: Hello World! <-- sau 2s

13. JavaScript Requests

⚡️ JSON

JSON
const jsonObj = {
name: 'Rick',
id: '11A',
level: 4,
};

⚡️ XMLHttpRequest: là một API ở mức trình duyệt cho phép khách hàng tạo kịch bản chuyển dữ liệu thông qua JavaScript, KHÔNG phải là một phần của ngôn ngữ JavaScript.

XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'mysite.com/getjson');

⚡️ GET: lấy tài nguyên từ máy chủ.

GET
const req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', '/getdata?id=65');
req.onload = () => {
console.log(xhr.response);
};

req.send();

⚡️ POST: gửi dữ liệu đến máy chủ.

POST
const data = {
fish: 'Salmon',
weight: '1.5 KG',
units: 5,
};
const xhr = new XMLHttpRequest();
xhr.open('POST', '/inventory/add');
xhr.responseType = 'json';
xhr.send(JSON.stringify(data));

xhr.onload = () => {
console.log(xhr.response);
};

⚡️ fetch api

fetch api
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
apikey: apiKey,
},
body: data,
}).then(
(response) => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
},
(networkError) => {
console.log(networkError.message);
},
);

⚡️ JSON Formatted

JSON Formatted:
fetch('url-that-returns-JSON')
.then((response) => response.json())
.then((jsonResponse) => {
console.log(jsonResponse);
});

⚡️ promise url parameter fetch api: Nếu bạn muốn truyền đường dẫn (URL) như một tham số vào một hàm sử dụng Promise và Fetch API, bạn có thể tạo một hàm chấp nhận tham số là URL, và sử dụng fetch để tạo yêu cầu đến đường dẫn đó. Dưới đây là một ví dụ:

promise url parameter fetch api
function fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then((data) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}

// Sử dụng hàm fetchData với một URL cụ thể
const specificURL = 'https://api.example.com/data';
fetchData(specificURL)
.then((data) => {
console.log('Data:', data);
})
.catch((error) => {
console.error('Error:', error);
});

// Sử dụng hàm fetchData với một URL khác
const anotherURL = 'https://api.example.com/otherData';
fetchData(anotherURL)
.then((data) => {
console.log('Other Data:', data);
})
.catch((error) => {
console.error('Error:', error);
});

Trong ví dụ trên:

  • fetchData là một hàm nhận một tham số là URL và trả về một Promise.
  • Bên trong Promise, fetch được sử dụng để thực hiện yêu cầu đến URL được truyền vào.
  • Nếu yêu cầu thành công và có dữ liệu hợp lệ, resolve(data) được gọi để trả về dữ liệu.
  • Nếu có lỗi trong quá trình xử lý yêu cầu, reject(error) được gọi để xử lý lỗi.

⚡️ Fetch API Function

Trong ví dụ dưới:

  • fetch được sử dụng để tạo yêu cầu mạng. Nó trả về một Promise chứa đối tượng Response.
  • Dùng .then() để xử lý phản hồi của yêu cầu.
  • Trong then, kiểm tra nếu phản hồi không thành công (có mã trạng thái không thuộc khoảng 200-299), một lỗi sẽ được ném và xử lý trong khối catch.
  • Sử dụng .json() để chuyển đổi dữ liệu từ định dạng JSON.
  • Dùng catch để xử lý bất kỳ lỗi nào xuất hiện trong quá trình xử lý yêu cầu.
Fetch API Function
// Basic GET request
fetch('https://api.example.com/data')
.then((response) => {
// Check if the request was successful (status code in the range 200-299)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse the response as JSON
return response.json();
})
.then((data) => {
// Process the data
console.log(data);
})
.catch((error) => {
// Handle errors
console.error('Fetch error:', error);
});

// POST request with JSON payload
const postData = {
username: 'exampleUser',
password: 'examplePassword',
};

fetch('https://api.example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData),
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Fetch error:', error);
});

⚡️ async await syntax: Đây là cú pháp async/await trong JavaScript, một cơ chế giúp quản lý xử lý bất đồng bộ (asynchronous code) một cách dễ đọc và hiệu quả hơn.

Trong hàm async, từ khóa await được sử dụng để chờ một Promise được giải quyết (resolved). Nó chỉ có thể được sử dụng trong hàm async.

Để xử lý lỗi trong các hàm async, bạn có thể sử dụng cấu trúc try/catch.

async await syntax
const getSuggestions = async () => {
const wordQuery = inputField.value;
const endpoint = `${url}${queryParams}${wordQuery}`;
try {
const response = await fetch(endpoint, { cache: 'no-cache' });
if (response.ok) {
const jsonResponse = await response.json();
}
} catch (error) {
console.log(error);
}
};

II. Tài liệu tham khảo

Chia sẻ: