0% found this document useful (0 votes)
109 views18 pages

Callbacks and Promises

The document explains promises in JavaScript, which are objects representing the eventual completion or failure of asynchronous operations, and outlines their key states: pending, fulfilled, and rejected. It also discusses asynchronous programming, callback functions, and the distinction between callbacks and promises, highlighting how promises provide better error handling and avoid 'callback hell.' Additionally, examples illustrate the use of promises and async/await syntax for handling asynchronous tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views18 pages

Callbacks and Promises

The document explains promises in JavaScript, which are objects representing the eventual completion or failure of asynchronous operations, and outlines their key states: pending, fulfilled, and rejected. It also discusses asynchronous programming, callback functions, and the distinction between callbacks and promises, highlighting how promises provide better error handling and avoid 'callback hell.' Additionally, examples illustrate the use of promises and async/await syntax for handling asynchronous tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Front-End

JavaScript

Felix - IT Systems
Promise in JavaScript
A promise in JavaScript is an object that represents the eventual
completion or failure of an asynchronous operation.

A promise in JavaScript is like a guarantee that you'll get a result in the


future, but you don’t know exactly when. It’s commonly used when you
have to wait for something to happen, like getting data from a server.

It is used for handling asynchronous operations, such as making API calls


or reading files, in a more organized and readable way.
ASYNCHRONOUS
OPERATION
Asynchronous programming in JavaScript is a technique that allows a program to run multiple tasks simultaneously, rather than waiting for one task to
finish before starting the next.

Asynchronous JavaScript allows a program to start a long-running task and continue running other tasks in parallel. This is possible because asynchronous code
is non-blocking, meaning it doesn't block the flow of execution.
Key States of a Promise :

Pending: When you first create a promise, it’s in a "waiting" state, like
you're waiting for a delivery. It’s the initial state of a promise. The operation
is ongoing and not yet completed.

Fulfilled: The state of a promise when the asynchronous operation


completes successfully, resulting in a value.

Rejected: The state of a promise when the asynchronous operation fails,


resulting in an error.
Syntax :

let myPromise = new Promise((resolve, reject) => {


// Asynchronous operation
});
Example :

let orderPizza = new Promise(function(resolve, reject) {


let pizzaReady = false; // let's say they make the pizza successfully

if (pizzaReady) {
resolve("Pizza is here!"); // Fulfilled
} else {
reject("Pizza delivery failed."); // Rejected
}
});

orderPizza.then(function(message) {
console.log(message); // Logs: "Pizza is here!"
}).catch(function(error) {
console.log(error); // In case of failure
});
Example :

function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Data fetched successfully!"); // Fulfilled
} else {
reject("Error fetching data."); // Rejected
}
}, 2000); // Simulates a 2-second delay
});
}
// Using the promise
fetchData()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});

console.log("Fetching data...");
async and await
async: A keyword used to declare a function that will return a promise.

Syntax :
async function functionName() {
// Code goes here
}

await: A keyword that is used inside an async function to pause the


execution of the code until a promise is resolved or rejected.

Syntax: const result = await promise;


Example :

function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched successfully!");
}, 2000);
});
}
async function getData() {
console.log("Fetching data...");

const result = await fetchData(); // Waits for fetchData to resolve


console.log(result); // Logs: "Data fetched successfully!"
}
getData();
Thank
You
Front-End
JavaScript

Felix - IT Systems
Callback functions
A callback function in JavaScript is a function that is passed as an
argument to another function and gets executed after the main function
completes its task. It's like saying, "Do this first, and when you're done,
call this other function.”

Callbacks can be either named functions or anonymous (inline) functions,


and they form the foundation for more complex asynchronous patterns
like Promises and async/await in modern JavaScript.
DISTINCTION BETWEEN CALLBACK
FUNCTIONS AND PROMISES:

Callback Functions:
• Functions passed as arguments and executed after a task completes.
• Can lead to "callback hell" if nested too deeply, making the code hard to read.

Promises:
•Used to handle asynchronous operations more smoothly.

•Provides better error handling with .then(), .catch(), and .finally() methods.

•Avoids "callback hell" by chaining tasks.


EXAMPLE:
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}

greet("Alice", sayGoodbye);
CALLBACK HELL
Callback hell happens when you have too many nested callback functions, one inside
another, making the code hard to read and maintain. It looks like a "pyramid of doom",
where each level adds more indentation, making it confusing and messy.

Imagine you need to do several tasks in a specific order, like:


1.Wake up
2.Eat breakfast
3.Go to work
4.Come back home

If each of these tasks is a callback function that only starts after the previous one is
completed, the code structure can become deeply nested, which makes it hard to
understand and debug.
EXAMPLE:
function wakeUp(callback) {
console.log("Waking up");
setTimeout(callback, 1000)
}

function eatBreakfast(callback) {
console.log("Eating breakfast");
setTimeout(callback, 1000)

function goToWork(callback) {
console.log("Going to Work");
setTimeout(callback, 1000)
}

function comeBackHome(callback) {
console.log("Coming back home");
setTimeout(callback, 1000)
}

wakeUp(() => {
eatBreakfast(() => {
goToWork(() => {
comeBackHome(() => {
console.log("Finally done for the day.")
})
})
})
})
Thank
You

You might also like