Previously we get data from:
XMLHttpRequest
Use XMLHttpRequest() to get data from HTTP
XML was popular back then, but now we have JSON XML structure data to transfer, just like JSON Sync JSON objects in local storage Read more about XMLHttpRequest
Add Event Listener
listening event: readystatechange request open / initialize = 1 request sent in progress = 2 other failed, pending code... (học rồi mà chưa note) Free open API
Cũng chưa note lại một số open API để thực tập 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
YOU DONT KNOW HOW LONG YOU WOULD WAIT Promise API
callback == promise
new Promise == define callback function myPromise.then() == execute a callback function
A better way to structure async code
Pass params into Promise using Closures
Promises Chaining
Instead of...
too many error duplicates We use promise chanining...
Fetch API
fetch == XMLHttpRequest
but no worry about readystatechange we don’t have to worry about IF it is completed we just need to check how it is succeeded (404 or 400 or 200)
Fetch will return a Promise
A Promise that resolve to a return value which can be used with .then() and catch(error) but we have to CHAIN promise to convert into object
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..
just like Fetch, but in general concept of a Function A Promise that resolve to a return value A Promise that reject to a throw new error
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