JavaScript Asynchronous Programming

print(“Line 1”)
print(“Line 2”)
print(“Line 3”)

JavaScript Runtime

  1. The JavaScript Engine, which handles JS code execution, is made up of the following components:
  • Memory Heap: The section of the JS Engine that allocates memory for the variables and functions of the code being run.
  • Call Stack: The single-threaded stack in which each execution context stacks up as the code is run. The event loop is constantly examining the call stack, which is a Last-In-First-Out (LIFO) queue, to determine whether any functions need to be performed. It continues to add any function calls it detects while executing to the call stack and executes them in the sequence of LIFO.
const secondFunction = () => console.log(‘calling second function’);const firstFunction = () => {      console.log(‘start first function’);      secondFunction;      console.log(‘first function end’);};firstFunction();
  • The firstFunction method is called, and the call stack is updated with the first execution context.
  • The initial console log is executed as the next statement on the Call Stack, is logged, and is then removed from the stack.
  • The following sentence calls another function, secondFunction(), which generates a new execution context for secondFunction.
  • The console log is added to the Call Stack, run, and removed from the stack in the first statement of secondFunction.
  • Because it is the end of secondFunction, the context for secondFunction is removed from the stack.
  • Finally, the firstFunction’s last console statement is performed, and firstFunction is completed and removed from the Call Stack.
start first function
calling second function
first function end
const secondFunction = () => setTimeout(() => console.log(‘calling second function’), 1000);const firstFunction = () => {      console.log(‘start first function’);      secondFunction;      console.log(‘first function end’);};firstFunction();
  • The firstFunction method is called, and the call stack is updated with the first execution context.
  • The initial console log is executed as the next statement on the Call Stack, is logged, and is then removed from the stack.
  • The following sentence calls another function, secondFunction(), which generates a new execution context for secondFunction.
  • There is a setTimeout of 1 second (1000 ms) in secondFunction. The setTimeout JavaScript function is processed simultaneously by the browser. When the setTimeout() method is used, a new execution context is produced and added to the top of the stack. The timer is generated alongside the callback and sits on a different thread in the Web API, where it runs asynchronously for 1 second without interfering with the main code flow.
  • The setTimeout() method returns and the Call Stack is cleaned.
    The secondFunction() method is the same.
  • The firstFunction’s last console statement is performed, and firstFunction is completed and removed from the Call Stack.
  • After 1 seconds, the timer is removed from the Web API, and the related callback function is relocated to the Message Queue. It sits there until the execution stack is empty, at which point it is taken up by the Event Loop.
  • The Event Loop will keep an eye on the message queue and the Execution Stack at all times. When the execution stack is empty, it moves the callback from the Message Queue to it. As a result, a callback execution context is established, and the console log is executed, finished, and removed from the stack.
start first function
first function end
undefined
calling second function

Callbacks

const asyncResponse = callback => { 
setTimeout(() => callback (‘Response from asynchronous function’), 1000);
}
asyncResponse (response => console.log(response))
function logAsyncResponse(response) {
console.log(response);
}
asyncResponse(logAsyncResponse);

Promises

const myPromise = new Promise((resolve, reject) => {
if (Math.random() * 10 <= 5) {
resolve('Promise success!');
}
reject(new Error('Promise failed'));
});
  • Pending: This is the state in which the promise is while it waits for the event to finish, hence it is said to be in the pending state.
  • Settled/Resolved: The promise is said to be settled or resolved once the asynchronous event has finished and the result has been received.
  • Fulfilled: It is considered to be fulfilled when the event is performed satisfactorily, the promise is fulfilled, and the reaction is accessible.
  • Rejected: If an error occurred throughout the procedure, the promise is said to be rejected.
  • resolve(value): This function is used to convey the promise’s success response. This will set the Promise Status to fulfilled. The value supplied as part of this function will be set as the promised value.
  • reject(error): This function is used to convey the promise’s error response. This will set the Promise Status to rejected. The error passed as a parameter to this function will be set to the promised value.
  1. then() accepts two callbacks:
  • When the promise is resolved or settled, the first callback function is run.
  • When the promise is refused, the second callback function is called.
myPromise.then(success => {
console.log(success);
}, error => {
console.log(error);
});
  • Only handle success:
myPromise.then(success => {
console.log(success);
});
  • Only handle error:
myPromise.then(null, error => {
console.log(error);
});
myPromise.then(success => {
console.log(success);
})
.catch(error => console.log(error));

Async Await

const asyncFunc = async () => return "Async Function"asyncFunc().then((result => console.log(result) //Async Function
const asyncFunc = async () => return Promise.resolve("Async Function")asyncFunc().then((result => console.log(result) //Async Function
const asyncFunc = async () => return Promise.reject(new Error('This promise is rejected with error!'));asyncFunc().catch(error => console.log(error));

Await

const printLanguage = language => {
const promise= new Promise( (resolve) => {
setTimeout(() =>{
console.log(language);
resolve(language);
}, 2000);
}
);
return promise;
}
async function getLanguage(){
const firstLanguage = await printLanguage("JavaScript");
const secondLanguage = await printLanguage("java");
return secondLanguage;
}
getLanguage().then((response)=>{
console.log(response);
});
async function getLanguage(){
const [firstLanguage, secondLanguage] = await Promise.all([printLanguage("JavaScript"),printLanguage("java")]);
return secondLanguage;
}
getLanguage().then((response)=>{
console.log(response);
});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store