JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations.
Example:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < title ></ title > </ head > < body > < div id = "message" ></ div > < script > var msg = document.getElementById("message"); function f1() { setTimeout(function () { msg.innerHTML += " < p >f1 is starting</ p > "; msg.innerHTML += " < p >f1 is ending</ p > "; }, 100); } function f2() { msg.innerHTML += " < p >f2 is starting</ p > "; f1(); msg.innerHTML += " < p >f2 is ending</ p > "; } f2(); </ script > </ body > </ html > |
Output
f2 is starting f2 is ending f1 is starting f1 is ending
Now, we can see after executing setTimeout(f1, 100), our program is not waiting for the timer to finish it but it is jumping on the next statement immediately. This happens because if we want to execute some event, JavaScript puts the event in the event queue and continues the normal execution of the program. The engine periodically looks in the event queue to see if some event needs to be called or not.
But we may want our program to wait until some particular event or work is completed before processing further commands.
An asynchronous function is implemented using async, await, and promises.
- async: The “async” keyword defines an asynchronous function.
Syntax async function FunctionName(){ ... }
- await: The “async” function contains “await” that pauses the execution of “async” function. “await” is only valid inside the “async” function.
- Promise: A Promise is a proxy value. It tells us about the success/failure of the asynchronous event. A Promise must contain resolve() or reject() call or else the consumer of the Promise will never know whether Promise is fulfilled or not. If that happened then the program will keep waiting for await and that code block will never be executed further. There is a lot more to Promise but we can make Asynchronous function without any deep knowledge of it.
Example: Let’s redo the above example using the Asynchronous function.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < title ></ title > </ head > < body > < div id = "message" ></ div > < script > var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += " < p >f1 is starting</ p > "; msg.innerHTML += " < p >f1 is ending</ p > "; resolve(); }, 100); }) } async function f2() { msg.innerHTML += " < p >f2 is starting</ p > "; // Engine waits for f1() to finish it's // execution before executing the next line await f1(); msg.innerHTML += " < p >f2 is ending</ p > "; } f2(); </ script > </ body > </ html > |
Output:
f2 is starting f1 is starting f1 is ending f2 is ending
In the above example, the program waits for f1() to complete its execution before proceeding further. The “await” stops the execution of that code segment until a Promise is received. The resolve() is used to resolve the Promise. It means the Promise is fulfilled. Similar to resolve, we can also use reject() to know the Promise is rejected. The reject() function is mainly used for debugging and error purpose, we don’t need to dig deep into it for now.
Example: If we want the Promise to return some value, we can pass it in resolve(variable).
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < title ></ title > </ head > < body > < div id = "message" ></ div > < script > var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += " < p >f1 is starting</ p > "; msg.innerHTML += " < p >f1 is ending</ p > "; resolve(1); }, 100); }) } async function f2() { msg.innerHTML += " < p >f2 is starting</ p > "; var p = await f1(); if (p == 1) msg.innerHTML += " < p >Promise Received</ p > " msg.innerHTML += " < p >f2 is ending</ p > "; } f2(); </ script > </ body > </ html > |
Output:
f2 is starting f1 is starting f1 is ending Promise Received f2 is ending
Waiting for Multiple Promises: What if we had to wait for multiple functions? We have two ways of doing it.
Example: We can write multiple await statements sequentially.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < title ></ title > </ head > < body > < div id = "message" ></ div > < script > var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += " < p >f1 is starting</ p > "; msg.innerHTML += " < p >f1 is ending</ p > "; resolve(); }, 1000); }) } function f3() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += " < p >f3 is starting</ p > "; msg.innerHTML += " < p >f3 is ending</ p > "; resolve(); }, 1000); }) } async function f2() { msg.innerHTML += " < p >f2 is starting</ p > "; await f1(); await f3(); msg.innerHTML += " < p >f2 is ending</ p > "; } f2(); </ script > </ body > </ html > |
Output
f2 is starting f1 is starting f1 is ending f3 is starting f3 is ending f2 is ending
- In the above example, first we get
f2 is starting
- Then after 1 second we get
f1 is starting f1 is ending
- Then after another 1 second, we get
f3 is starting f3 is ending f2 is ending
Example: The second way to wait for multiple Promises is to run the Promises in parallel using Promise.all(iterable object).
Syntax:
await Promise.all(iterable object);
Example:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < title ></ title > </ head > < body > < div id = "message" ></ div > < script > var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += " < p >f1 is starting</ p > "; msg.innerHTML += " < p >f1 is ending</ p > "; resolve(); }, 1000); }) } function f3() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += " < p >f3 is starting</ p > "; msg.innerHTML += " < p >f3 is ending</ p > "; resolve(); }, 1000); }) } async function f2() { msg.innerHTML += " < p >f2 is starting</ p > "; await Promise.all([f1(), f3()]); msg.innerHTML += " < p >f2 is ending</ p > "; } f2(); </ script > </ body > </ html > |
Output
f2 is starting f1 is starting f1 is ending f3 is starting f3 is ending f2 is ending
- The output is the same as the previous code, but in this case, the program will output
f2 is starting
- Then wait for 1second and output
f1 is starting f1 is ending f3 is starting f3 is ending f2 is ending
Since f1() and f3() are running in parallel we do not need to wait another 1 second before executing f3(). In simple words, the timer of setTimeout() in f1() and f3() starts at the same time.
Note: We can also implement asynchronous behavior using only Promises without async/await and callbacks, refer to the following link for that: