Callbacks in JS

In JS, callbacks are functions that get executed after certain event is triggered.

console.log ("This is the first statement")

setTimeout(()=>{
    console.log("This is inside callback that gets pushed 
    to message queue after 1000 ms")
},1000)

console.log ("This is the last statement")

Asynchronous programming

Now let me talk about Asynchronous programming. Unlike C language, where the instructions are executed in sequence, In JS, instructions may get executed Asynchronously. Whenver JS encounters blocking instruction, it is delegated to corrospnding API for hanldling it and JS engine keeps on running the instructions until stack becomes empty. When the stack is empty and Message Queue contains some messages pushed by APIs after the occurance of events, event loop will ask JS engine to run the tasks in Queue in FIFO order.

console.log ("This is the first statement")

fetch("https://jsonplaceholder.typicode.com/users/1").then((res)=>{
res.json().then(res => {
    console.log(res)
})
})

console.log ("This is the last statement")

Web development and Automation testing

solutions delivered!!