Skip to content

Promises, Async/Await, Callback

🔎 async function là gì?

async/await là cú pháp giúp viết code bất đồng bộ (asynchronous) trông giống như code tuần tự
được đưa vào ECMAScript 2017 (ES8)
Callback

Cách cũ (ES5 – dùng callback hoặc Promise.then)

Promise là cách tiếp cận xử lý async và callback.
nó chỉ là một Object, đại diện cho future value
useFeature, featureHandler
sau khi hoàn thành, nó sẽ trả lại một giá trị
A Promise is an object that represents the eventual result of an asynchronous operation.
It can be in one of three states:
- Pending – the async operation hasn’t finished yet.
- Fulfilled – the operation succeeded (calls resolve).
- Rejected – the operation failed (calls reject).
More often than not, you will be using Promises when working with APIs rather than creating them yourself. However, it is important to understand how they work.
image.png
Không dùng Arrow Function
Dùng Arrow Function

Cách mới (ES8 – async/await)

👉 Kết quả giống nhau, nhưng async/await dễ đọc, dễ debug hơn.
The `async` keyword is used to define an asynchronous function, and the `await` keyword is used to wait for the Promise to resolve. We can use `try` and `catch` blocks to handle the resolved and rejected Promises.

🔁 So sánh với ES5

ES5 (2010): chưa có Promise, phải dùng callback hell.
ES6 (2015): giới thiệu Promise.
ES8 (2017): giới thiệu async/await, viết code trên Promise cho gọn.

Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.