Web Programming
Lecture 7
Javascript - 3
Callbacks, Promises, Async/await,
Eventloop
Callbacks
A callback is a function passed as an argument to another function.
This technique allows a function to call another function
function calculate(a, b, callback) {
let result = callback(a, b);
[Link]("Result:", result);
}
function add(x, y) {
return x + y;
}
calculate(5, 3, add);
Browser APIs
1. The Browser Web APIs are a set of built-in APIs provided by modern web
browsers that allow developers to interact with various browser features.
2. Some of the browser APIs are DOM API, Fetch API, Storage APIs, etc.
3. Some of the APIs are asynchronous and run in a background thread, such
as fetch API.
4. Some APIs run in the main thread, such as DOM manipulation, storage APIs
(session storage, local storage, etc.)
Asynchronous
JavaScript is single-threaded, meaning it executes one task at a
time. However, asynchronous programming allows it to handle
multiple tasks without blocking execution.
Synchronous Code
(Executes One Task at a Time)
Promises
A promise represents a future value that may either
succeed or fail.
It starts in the Pending state and transitions to either:
Resolved (fulfilled with a value)
Rejected (failed with an error)
Most asynchronous Browser APIs return a promise on the
main thread.
Once execution completes, the promise is resolved with a
value or rejected with an error.
To access the result, use .then(callback), and for errors, use
.catch(callback).
Fetch API
Async/Await
● Makes async code look synchronous.
● Uses try...catch for error handling.
Async/Await
async function example(throwError=false) {
if (throwError) throw new Error("Promise rejected");
return 42;
}
[Link](example()); // Output: Promise { 42 }
example().then([Link]); // Output: 42
example(true).catch((error)=>[Link]([Link]))
; // Promise rejected
Fetch api using JS
Event Loop
► When the fetch api completes asynchronously
(outside of main thread), it then calls the callback
passed in the then. But is the execution of
callback started immediately?
► The callback is actually placed in a queue.
► When the javascript thread is free, it takes a task
from the task queue and executes it.
► The Event Loop is what makes JavaScript
asynchronous. It allows JavaScript to handle
non-blocking operations, even though it's
single-threaded.
How Does Event Loop
Works?
JavaScript has:
1. Call Stack → Handles function execution (one
at a time).
2. Web APIs → Handles asynchronous tasks (like
setTimeout, fetch).
3. Callback Queue → Stores completed async
tasks waiting to run.
4. Event Loop → Moves tasks from the Callback
Queue to the Call Stack when it's empty.
Event Loop
Event Loop
Event Loop
Event Loop
Event Loop
Event Loop
Event Loop
Event Loop
Event Loop
Event Loop
If there were some instructions after main function call,
would cb still be placed on the call stack?
Event Loop
No, because when JavaScript runs for the first time, it
creates a global execution context, which is placed on the
call stack.
All instructions outside a function belong to this global
execution context.
The global execution context remains on the stack until
the entire script finishes execution.
As a result, the callback won’t be added to the call stack
until the script has fully executed—including the two
instructions following the main function call.
2 types of queues for callback
1. Microtask Queue (also called Job Queue)
2. Callback Queue (also called Task Queue or Macrotask
Queue)
Microtask Queue (Job Queue)
● Used for: Promises
● Higher priority than the Callback Queue.
● Executes immediately after synchronous code (before any
tasks from the Callback Queue).
Callback Queue (Macrotask Queue)
● Used for: setTimeout(),setInterval(),event handlers
● Lower priority than the Microtask Queue.
● Runs after all microtasks are cleared.
Micro/Callback(Macro) Queue
[Link]("1: Start");
setTimeout(() => [Link]("4: setTimeout"), 0); // Goes to Callback
Queue
[Link]().then(() => [Link]("3: Promise resolved")); //
Goes to Microtask Queue
[Link]("2: End");
Output
1: Start
2: End
3: Promise resolved <-- Microtask runs before setTimeout
4: setTimeout
Immediately Invoked
Function Expression
● Immediately Invoked Function Expressions
(IIFE) are JavaScript functions that are
executed immediately after they are defined.
Immediately Invoked
Function Expression
// standard IIFE
(function () {
// statements…
})();
// arrow function variant
(() => {
// statements…
})();
// async IIFE
(async () => {
// statements…
})();