[go: up one dir, main page]

0% found this document useful (0 votes)
19 views15 pages

Javascript Promises

The document explains the differences between synchronous and asynchronous JavaScript, highlighting that synchronous code executes sequentially and can block operations, while asynchronous code allows tasks to run in the background without blocking. It covers concepts such as callbacks, promises, and the importance of promise chaining to avoid callback hell. Additionally, it provides real-life analogies and examples to illustrate these concepts effectively.

Uploaded by

kauramrit1128
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views15 pages

Javascript Promises

The document explains the differences between synchronous and asynchronous JavaScript, highlighting that synchronous code executes sequentially and can block operations, while asynchronous code allows tasks to run in the background without blocking. It covers concepts such as callbacks, promises, and the importance of promise chaining to avoid callback hell. Additionally, it provides real-life analogies and examples to illustrate these concepts effectively.

Uploaded by

kauramrit1128
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

https://meet.google.

com/jqw-dqhv-nse
Asynchronous and Synchronous Function
1. What is Synchronous JavaScript?

Synchronous JavaScript means code is executed sequentially, one step at a time.

Each operation must finish before the next one starts.

🧩 Characteristics:

 Code runs in order, from top to bottom.

 Blocking behavior: if one task takes time (like a large computation), it blocks the

rest.

 Easier to debug because the flow is predictable.

Example
console.log("Task 1");
console.log("Task 2");
console.log("Task 3");

Here, JavaScript does not move to the next line until the current one is fully executed.

2. What is Asynchronous Function ?

Due to synchronous programming, sometimes imp instructions get blocked due to


some previous instructions, which causes a delay in the UI.
Asynchronous code execution allows to execute next instructions immediately and
doesn't block the flow.

Asynchronous JavaScript allows certain tasks to run in the background (like API
calls, timers, or file reading , weather API) without blocking the rest of the code.
🧩 Characteristics:

 Tasks are non-blocking.


 Uses the Event Loop and Callback Queue.
 Often used for operations like fetching data from a server.

🔧 Mechanisms of Async:

1. Callbacks
2. Promises
3. async/await (built on top of promises)

Feature Synchronous Asynchronous

Execution Line by line Skips long tasks, resumes later

Blocking Yes No

Use Case Simple logic API calls, timers, file operations

Tools Used Normal setTimeout, Promises, async/await


functions

CALLBACK
Callback : A callback function is a function passed as an argument to another function
and is executed after some operation has been completed.

In JavaScript, functions are first-class citizens — which means functions can be:

 Assigned to variables,
 Passed as arguments,
 Returned from other functions.

Note : A callback is a function that is called back at a later time — usually after a task is done.
function doSomething(callback) {
console.log("Doing something...");
callback(); // calling the callback function
}
function afterDone() {
console.log("Finished the task!");
}

doSomething(afterDone);

For Asynchronous
console.log("Start");

setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);

console.log("End");

🎯 Why Use Callbacks?

 To handle asynchronous operations (e.g., API calls, timers).


 To execute code in order, even when some parts take time.
 Common in functions like setTimeout(), event listeners, and AJAX calls.

🔄 Real-life Analogy:

Imagine you're ordering a pizza:

 You give your phone number (callback function) to the restaurant.


 They’ll call you back when the pizza is ready (task completed).
 Meanwhile, you can do other tasks (non-blocking).
⚠️Callback Hell
When callbacks are nested inside other callbacks — it leads to messy and hard-to-read code:

doTask1(function () {

doTask2(function () {

doTask3(function () {

// and so on...

});

});

});

This is called callback hell or the pyramid of doom.

✅ Solution: Use Promises or async/await for cleaner, more readable code.

PROMISES

What is a Promise in JavaScript?


A Promise is like a guarantee of a future result in JavaScript — either success
or failure.
It's used to handle asynchronous operations, like:
 Fetching data from a server (API)
 Reading a file
 Setting a timer, etc.
🎯 Real-Life Analogy:

Imagine you order a pizza online.

 The pizza shop gives you a promise:


“We’ll deliver your pizza in 30 minutes.”

There are only 3 possible outcomes:

1. ✅ You get the pizza (Promise fulfilled)

2. ❌ They call and say they can't deliver (Promise rejected)

3. ⏳ You are still waiting (Promise is pending)

State Meaning

Pending The result hasn't come yet

Fulfilled Operation completed successfully

Rejected Operation failed

📦 Simple Syntax of a Promise:

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

// some task

});

 resolve(): Call this when the task is successful.

 reject(): Call this if something goes wrong.


🔁 .then() and .catch() in JavaScript Promises

✅ .then() – Used when the promise is successful (fulfilled)

❌ .catch() – Used when the promise fails (rejected)

📤 When to Use .then():

Use .then() to:

 Handle the successful result of a promise

 Do something after an async operation completes

📛 When to Use .catch():

Use .catch() to:

 Handle errors like network failures or rejected promises

 Prevent your app from crashing


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

let isPizzaAvailable = true;

if (isPizzaAvailable) {

resolve("Pizza delivered! 🍕");

} else {

reject("Sorry, pizza not available 😢");

});

// How to use it

pizzaOrder

.then(function(result) {

console.log(result); // if resolve is called

})

.catch(function(error) {

console.log(error); // if reject is called

});

💡 Pro Tip:

You can chain multiple .then() blocks, and use one .catch() at the end to catch any errors:

someAsyncFunction()

.then(step1)

.then(step2)

.then(finalStep)

.catch(handleAnyError);
✅ What is Promise Chaining?

Promise chaining means calling multiple .then() methods one after another so that each
.then() receives the result of the previous one.

This lets you:

 Run asynchronous tasks in sequence


 Keep your code clean and readable
 Avoid callback hell

doSomething()

.then(result1 => doSomethingElse(result1))

.then(result2 => doAnotherThing(result2))

.then(finalResult => {

console.log("All done!", finalResult);

})

.catch(error => {

console.log("Something went wrong:", error);

});

🧠 Real-Life Analogy:

🍕 Ordering food online:

1. You order pizza → step 1 .then ()

2. You get confirmation → step 2

3. You receive the delivery → step 3

4. You eat and enjoy → final step

Why Use Promise Chaining?


Benefit Description
🚫 Avoid callback hell Looks cleaner than nested callbacks
✅ Executes in order Ensures each step runs after the previous
🧠 Passes data forward Each .then() gets the previous result

1. What is synchronous code in JavaScript?


A) Code that runs in any random order
B) Code that runs only when a promise is rejected
C) Code that runs line by line, blocking the next task until it finishes
D) Code that always runs after 5 seconds

2. What is the main disadvantage of synchronous code?

A) It uses too many variables


B) It doesn’t support JavaScript
C) It blocks the execution of other code
D) It’s harder to understand

3. . What is a callback function?

A) A function that calls itself


B) A function that runs before the main function
C) A function passed as an argument to another function
D) A function that only runs on error

4. What is callback hell?

A) A place where functions don’t work


B) A nested structure of callbacks that makes code hard to read
C) A type of error in JS
D) An error caused by using promises incorrectly

5. What is a Promise in JavaScript?

A) A method that deletes variables


B) An object representing future completion of an async task
C) A built-in loop
D) A CSS property

6. What are the 3 states of a Promise?

A) Start, Continue, End


B) Begin, Error, Complete
C) Pending, Fulfilled, Rejected
D) Waiting, Working, Done

7. What happens if you return a value inside .then()?


A) It gets ignored
B) It's passed to the next .then()
C) It stops the chain
D) It throws an error

8. Which is the correct way to handle both success and error?

A) .then().then()
B) .error().resolve()
C) .then().catch()
D) .done().fail()

9. Which of these is NOT a valid state of a Promise?

A) Pending
B) Completed
C) Fulfilled
D) Rejected

Script.js

// let promise = new Promise((resolve, reject)=>{

// console.log("I am a promise");

// // resolve("Success")

// reject("Some network error")

// })

// let pizzaOrder = new Promise(function(resolve, reject) {

// let isPizzaAvailable = true;

// if (isPizzaAvailable) {

// resolve("Pizza delivered! 🍕");

// } else {

// reject("Sorry, pizza not available 😢");

// }

// });
// // How to use it

// pizzaOrder

// .then(function(result) {

// console.log(result); // if resolve is called

// })

// .catch(function(error) {

// console.log(error); // if reject is called

// });

//Promise Chaining

function asyncFunc1() {

return new Promise((resolve, reject) => {

setTimeout(() => {

console.log("data1");

resolve("success");

}, 4000);

});

function asyncFunc2() {

return new Promise((resolve, reject) => {

setTimeout(() => {

console.log("data2");

resolve("success");

}, 4000);

});

console.log("Fetching data 1");

asyncFunc1().then((res)=>{

console.log(res)
console.log("Fetching data 2")

asyncFunc2().then((res)=>{

console.log(res)

})

})

// function getData(dataId, getNextData){

// return new Promise((resolve,reject)=>{

// setTimeout(()=>{

// console.log("data",dataId)

// // resolve("success")

// reject("Error occured")

// if(getNextData){

// getNextData();

// }

// },4000);

// });

// }

// const getPromise =()=>{

// return new Promise((resolve, reject)=>{

// console.log("I am a promise")

// //resolve("Success")

// reject("network error")

// })

// }

// let promise = getPromise();

// promise.then((res)=>{

// console.log("Promise Fulfilled", res)

// });
// promise.catch((err)=>{

// console.log("Promise rejected",err)

// })

// function sum(a,b){

// console.log(a+b)

// }

// function calculator(a,b , sumCallback){

// sumCallback(a,b)

// }

// calculator(1, 2 ,sum )

// console.log("Start");

// setTimeout(() => {

// console.log("This runs after 2 seconds");

// }, 2000);

// console.log("End");

// let age =19;

// if(age>=18){

// if(age >=60){

// console.log(senior)

// }

// else {

// console.log("middle ")

// }
// }else{

// console.log("child")

// }

// for(let i=0;i<5;i++){

// let str=""

// for(j=0; j<5 ; j++){

// str = str+j;

// }

// console.log(i,str)

// }

// function getData(dataId ,getNextData){

// setTimeout(()=>{

// console.log("data" , dataId)

// if(getNextData){

// getNextData();

// }

// },2000);

// }

// getData(1 , ()=>{

// getData(2 ,()=>{

// getData(3);

// });

// });

// console.log("Task 1");

// console.log("Task 2");

// function hello(){
// console.log("hello")

// }

// setTimeout(hello,2000) //2s = 2000ms

// console.log("Task 3");

You might also like