[go: up one dir, main page]

0% found this document useful (0 votes)
6 views16 pages

Advanced JavaScript

JavaScript Promises are objects that represent the eventual completion or failure of an asynchronous operation, existing in three states: pending, fulfilled, or rejected. They simplify asynchronous code, improve readability, and enhance error handling compared to traditional callback methods. Advanced methods like Promise.all(), Promise.allSettled(), and async/await further streamline asynchronous programming in JavaScript.

Uploaded by

rata.divya2022
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)
6 views16 pages

Advanced JavaScript

JavaScript Promises are objects that represent the eventual completion or failure of an asynchronous operation, existing in three states: pending, fulfilled, or rejected. They simplify asynchronous code, improve readability, and enhance error handling compared to traditional callback methods. Advanced methods like Promise.all(), Promise.allSettled(), and async/await further streamline asynchronous programming in JavaScript.

Uploaded by

rata.divya2022
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/ 16

JavaScript Promises

Asynchronous:

Functions running in parallel with other functions are


called asynchronous.

A good example is JavaScript setTimeout()

setTimeout(myFunction, 3000);

function myFunction() {

console.log("Hello BCA Class");

}
What are JavaScript Promises?

Definition:

A Promise is a JavaScript object that promises to deliver the result


of a task (usually asynchronous) upon its completion in the future—
whether that task is completed successfully or fails.

It can be in one of three states:

 Pending: The task is in the initial state.

 Fulfilled: The task was completed successfully, and the result


is available.

 Rejected: The task failed, and an error is provided.

Why Use Promises?

1) Asynchronous code ko easy aur readable banata hai


2) Callback hell se bachata hai
3) Error handling better hoti hai
Callback Hell vs Promise

Callback Hell:

Use Promises instead:


Promises Syntax:

Example:

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

alert("Hello")

resolve("Hello, I am a promise")

})

console.log("Hello One")

setTimeout(function() {

console.log("Hello Two in 2 seconds")

}, 2000)

console.log("Hello Three")
.then() / .catch()

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

console.log("Promise is pending")

setTimeout(() => {

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

resolve(true)

}, 5000)

})

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

console.log("Promise is pending")

setTimeout(() => {

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

reject(new Error("I am an error"))

}, 5000)

})

// To get the value


p1.then((value) => {

console.log(value)

})

// To catch the errors

// p2.catch((error) => {

// console.log("some error occurred in p2")

// })

p2.then((value)=>{

console.log(value)

},(error)=>{

console.log(error)

})

Let’s See Advanced Promise Methods and Patterns for Effective


Async Handling

1. Promise.all() Method

Waits for all promises to resolve and returns their results as an


array. If any promise is rejected, it immediately rejects.
Promise.all([

Promise.resolve("Task 1 completed"),

Promise.resolve("Task 2 completed"),

Promise.reject("Task 3 failed")

])

.then((results) => console.log(results))

.catch((error) => console.error(error));

2. Promise.allSettled() Method

Waits for all promises to settle (fulfilled or rejected) Method and


returns an array of their outcomes.

Promise.allSettled([

Promise.resolve("Task 1 completed"),

Promise.reject("Task 2 failed"),

Promise.resolve("Task 3 completed")

])

.then((results) => console.log(results));


3. Promise.race() Method

Promise.race() Method resolves or rejects as soon as the first


promise settles.

Promise.race([

new Promise((resolve) =>

setTimeout(() =>

resolve("Task 1 finished"), 1000)),

new Promise((resolve) =>

setTimeout(() =>

resolve("Task 2 finished"), 500)),

]).then((result) =>

console.log(result));

4. Chaining with Promise.prototype.then() Method

Allows sequential execution of promises, passing results to the next


.then() Method.

Promise.resolve(5)

.then((value) => value * 2) // Multiplies by 2

.then((value) => value + 3) // Adds 3

.then((finalValue) => console.log(finalValue)); // Logs: 13


Async / Await:

What is async in JavaScript?

The async keyword is used to declare an asynchronous function.

An async function always returns a Promise — even if you return a


simple value.

Why use async?

To use the await keyword inside a function, the function must be


marked as async.

What is await in JavaScript?

The await keyword is used inside an async function to pause the


execution until a Promise is resolved.

It waits for the Promise to finish — then returns the result.

Example:

async function weather() {

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

setTimeout(() => {

resolve("27 Deg")
}, 2000)

})

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

setTimeout(() => {

resolve("21 Deg")

}, 5000)

})

// delhiWeather.then(alert)

// bangaloreWeather.then(alert)

console.log("Fetching Delhi Weather Please wait ...")

let delhiW = await delhiWeather

console.log("Fetched Delhi Weather: " + delhiW)

console.log("Fetching Bangalore Weather Please wait ...")

let bangaloreW = await bangaloreWeather

console.log("Fetched Bangalore Weather: " + bangaloreW)

return [delhiW, bangaloreW]

}
const test = async () => {

console.log("Hello, I am waiting ")

const main1 = async () => {

console.log("Welcome to weather control room")

let a = await weather()

let b = await test()

main1()
ES6+ Features:

1. Arrow Functions (=>)

� What is it?

Arrow functions are a shorter and cleaner way to write functions in


JavaScript, introduced in ES6.
� Key Points:

 If the function has only one statement, you can skip {} and
return.

 If the function takes one parameter, you can skip the


parentheses too:

2. Template Literals

� What is it?

Template literals (or template strings) allow us to embed variables


inside strings and write multi-line strings easily using backticks (`
``).

� Before ES6 (using +):

let name = "Ravi";

console.log("Hello, " + name + "!");


� With Template Literals:

let name = "Ravi";

console.log(`Hello, ${name}!`);

� Multi-line Strings:

3. Destructuring (Objects & Arrays)

� What is it?

Destructuring is a shortcut to extract values from arrays or objects


and store them in variables.

� Object Destructuring:

const person = { name: "Ravi", age: 22 };

// Instead of:

let name = person.name;

let age = person.age;


// Use:

const { name, age } = person;

console.log(name); // Ravi

� Array Destructuring:
const colors = ["red", "green", "blue"];

// Instead of:

let first = colors[0];

let second = colors[1];

// Use:

const [first, second] = colors;

console.log(first); // red
THE END

You might also like