Async
Previously we get data from:
XMLHttpRequest
Use XMLHttpRequest() to get data from HTTP
Read more about XMLHttpRequest
This embedded link can't be shown.
Add Event Listener
Free open API
Callback Abstraction
How do we get return data from Ajax before the page finished loading?
When we make a normal XMLHttpRequest(), it would run synchronously (in top to down order)...
But if we put the XMLHttpRequest() in a function, and return a value, then use that value in the lower code, it would NOT WORK, because JS run asynchronously as default.
The time it takes for the XMLHttpRequest() to return data, would be too slow, during that the lower code would have finished executing...
Even if you return data with the right scope, it would not work...
A CALLBACK FUNCTION IS A FUNCTION WILL BE CALL IN ANOTHER FUNCTION...
For example, we add a function after a click event in addEventListener function...
We will apply this callback function abstraction to solve the asynchronous issue...
BUT, what if we want to do it synchronously with function, how do we do it?
NOTE: DON’T WAIT FOR SOMETHING TO FINISH BEFORE RUNNING OTHER THINGS
Promise API
callback == promise
A better way to structure async code
Pass params into Promise using Closures
Promises Chaining
Instead of...
We use promise chanining...
Fetch API
fetch == XMLHttpRequest
Fetch will return a Promise
User Fetch with Chaining and Arrow Function for optimal data fetching
Async / Await
async == Fetch in General Function
Async is used for FUNCTION
Async function always return a Promise..
await == .then() chaining in Promise
No more then() multiple times. We can just assign Promise to var using await.
What come after await must be a Promise object
Or in a simple term:
BEST PRACTICE
Tóm tắt:
Đọc thêm từ MDN JS
Async Fetch at Client side
This embedded link can't be shown.
This embedded link can't be shown.
