DEV Community

Discussion on: Learn callbacks, promises, Async/Await by Making Ice Cream 🍧🍨🍦

Collapse
 
raquelsartwork profile image
Raquel Santos | RS-coding

can you give examples of async JS in real world? I still find Difficult to know when I should use it. Thank you

Collapse
 
longthtran profile image
Long Tran • Edited

You are expected to know the definition of async task, also non-blocking IO (becasue you are JS developers :D ). Here is what I found on stackoverflow: "Point of an async Task is to let it execute in background without locking the main thread, such as doing a DownloadFileAsync".

Most of async task I cope with when coding in JS are: calling API, making a query to database/cache, reading/writing a file,... The reason they are called "async" because you call those functions which are not supposed to return the result "immediately". The moment you call the async task function (lets call func A), your CPU (main thread) is free and it could be used to do another task meanwhile the previous async task function A is in "pending" state waiting for the result to comes back. After then, your JS code shall run to the next line without being blocked at the line you call the async function A; this is not what we want, we expect the code runs sequentially from the top to bottom line by line in case the underneath code must use the result of A ;)

When to use Promise -> When your project is using ES5 or older version, or maybe you are dealing with some library are not written in async/await style.
For ex: a time I played with Google Cloud Storage API written with Promise/callback styles, having some listener method onFinish, onError,... You can wrap their code inside a Promise((resolve, reject) => {}), and your async function return that Promise. From now on, you are freely await your async function!
Sr for the long writing, hope it can help

Collapse
 
raquelsartwork profile image
Raquel Santos | RS-coding

thanl you so much for the explanation :) always a help