0% found this document useful (0 votes)
22 views

Promise in Js

A Promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises provide a clean and consistent way to work with asynchronous code. A Promise can be in one of three states: pending, fulfilled, or rejected. Promise.all waits for all promises to fulfill, while Promise.race waits for the first promise to fulfill or reject.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Promise in Js

A Promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises provide a clean and consistent way to work with asynchronous code. A Promise can be in one of three states: pending, fulfilled, or rejected. Promise.all waits for all promises to fulfill, while Promise.race waits for the first promise to fulfill or reject.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

*********************************PROMISE***********************************

1. What is a Promise in JavaScript?


A Promise is a built-in JavaScript object that holds future value for completion
or failure of an asynchronous operation.
It provides a clean and consistent way to work with asynchronous code.
-------------
2.How do you create a Promise?

You can create a new Promise using the Promise constructor. The constructor takes a
function with resolve and reject parameters. The resolve function is used to
fulfill the promise, while the reject function is used to reject it.

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


// Asynchronous operation
setTimeout(() => {
resolve('Operation completed successfully!');
}, 1000);
});
------------------------------
3.What are the three states of a Promise?

A Promise can be in one of three states:


Pending: Initial state, neither fulfilled nor rejected.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.
-----------------------------------------
4.What is the purpose of the then and catch methods in a Promise?

The then method is used to handle the fulfillment of a Promise, and the catch
method is used to handle its rejection.

myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});
---------------------------------------------------------
5.How do you handle multiple promises concurrently?

You can use Promise.all to wait for all promises to fulfill, or Promise.race to
wait for the first one to fulfilled or reject.

const promise1 = new Promise(/* ... */);


const promise2 = new Promise(/* ... */);

Promise.all([promise1, promise2])
.then(([result1, result2]) => {
console.log(result1, result2);
})
.catch((error) => {
console.error(error);
});

Promise.race([promise1, promise2])
.then((firstResolvedResult) => {
console.log(firstResolvedResult);
})
.catch((error) => {
console.error(error);
});
-----------------------------------------------------------------------------------
------------------------
6.What is chaining in Promises?

Chaining involves using multiple .then() calls to perform a sequence of


asynchronous operations.

promise1
.then((result1) => {
return result1 + 10;
})
.then((result2) => {
console.log(result2);
});
---------------------------------------------------------------------------
10.What is the difference between Promises and callbacks?

Promises provide a more structured and flexible way to handle asynchronous code
compared to callbacks.
Promises can be chained, and errors can be caught globally using catch.
-----------------------------------------------------------------------------------
--------

7.How do you convert callback-based function to Promises based function?


Example:-
->callback based function...
function addNumbersCallback(a, b, callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const result = a + b;
callback(null, result);
}, 1000);
}

// Callback function to handle the result


function callbackFunction(error, result) {
if (error) {
console.error('Error:', error);
} else {
console.log('Result:', result);
}
}

// Invoking the callback-based function


addNumbersCallback(3, 5, callbackFunction);

--> Promise based function(conversion of avobe program

function addNumbersPromise(a, b) {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const result = a + b;
resolve(result);
}, 1000);
});
}

addNumbersPromise(3, 5)
.then((result) => {
console.log('Result:', result);
})
.catch((error) => {
console.error('Error adding numbers:', error);
});
-----------------------------------------------------------
8.What is Promise rejection handling?

Rejections can be handled using the catch method or try...catch when using
async/await.

promise1
.then(/* ... */)
.catch((error) => {
console.error(error);
});
--------------------------------------------------------------------------
9.What is the purpose of the finally method in a Promise?

The finally method is used for cleanup operations, and it gets executed regardless
of whether the Promise is fulfilled or rejected.
javascript
Copy code
promise1
.then(/* ... */)
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log('Cleanup');
});

-----------------------------------------------------------------------------------

11.What is the difference between Promise.resolve and Promise.reject?


Promise.resolve creates a resolved promise with the given value, and Promise.reject
creates a rejected promise with the given reason.

const resolvedPromise = Promise.resolve('Resolved value');


const rejectedPromise = Promise.reject('Rejection reason');
---------------------------------------------------------------------------------

12.How do you handle errors in async/await?


Errors in async/await can be handled using try...catch.

async function asyncOperation() {


try {
const result = await promise1;
console.log(result);
} catch (error) {
console.error(error);
}
}
----------------------------------------------------------
13.Explain the event loop and the role of Promises.

Since javascript is a single threaded... Means the task are executed one after
another snychronsly.

It handles asynchronous task with the help of event loop.

All the async tasks are placed in MICROTASK queue with some event.

Once the call stack has executed synchronous task... Then event loop bring those
async task to call stack i.e. in the execution context for the execution in a non-
blocking way.

Promises play a key role in managing asynchronous operations within the event
loop,
making it easier to reason about and handle asynchronous code.

-----------------------------------------------------------------
14.How do you create a Promise that resolves or rejects after a delay?

You can use setTimeout within a Promise to introduce a delay before resolving or
rejecting.

const delayedPromise = new Promise((resolve, reject) => {


setTimeout(() => {
resolve('Operation completed after delay');
}, 2000);
});

---------------------------------------------
15.Explain async/await and how it relates to Promises.

async/await is a syntactic sugar for working with Promises.


The async keyword is used to define an asynchronous function, and await is used to
wait for a Promise to settle.

async function asyncOperation() {


const result = await promise1;
console.log(result);
}
-----------------------------------------------------------------------------------
---
16. Create a promise with some delay and pass the delay as user argument

const promiseInput = (delay) => {


return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`resolved in ${delay}`);
}, delay);
});
};

promiseInput(1000).then((result) => {
console.log(result);
});

###################### Promise.All related Questions ##############################

------------------------------------------------
Example1:-
const asyncOperation1=()=> {
return new Promise(resolve => {
setTimeout(() => {
resolve('Result from asyncOperation1');
}, 2000);
});
}

const asyncOperation2=()=> {
return new Promise(resolve => {
setTimeout(() => {
resolve('Result from asyncOperation2');
}, 1500);
});
}

Promise.all([asyncOperation1(), asyncOperation2()])
.then(results => {
console.log('All operations completed successfully:', results);
})
.catch(error => {
console.error('Error:', error.message);
});
---------------------------------------------------
Example2:-Implement Promise.All multiple api call...where it will wait for all api
to be resolved...if even a single is failed then...it returns rejected.

const fetchData = (url) => {


return fetch(url)
.then(response => response.json())
.catch(error => {
throw new Error(`Failed to fetch data from ${url}: ${error.message}`);
});
};

const urls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
];

const fetchPromises = urls.map(url => fetchData(url));

Promise.all(fetchPromises)
.then(dataArray => {
console.log('All data fetched successfully:', dataArray);
})
.catch(error => {
console.error('Error fetching data:', error.message);
});
-------------------------------------------------------------------
1. Explain the purpose of Promise.all and when you might use it.

Example Answer: Promise.all is used when you have multiple asynchronous tasks that
can be executed concurrently,
and you want to wait for all of them to complete before moving forward.
-------------------------------------------------------
2.What happens if one of the promises in Promise.all is rejected?

Example Answer: If any of the promises is rejected, the entire Promise.all is


rejected,
and the reason is the rejection reason of the first promise that was rejected.
-----------------------------------------------------------------------------------
----------------
3.Can you use Promise.all with a mix of asynchronous tasks and non-promises?

Example Answer: No, Promise.all expects an array of promises.


If you need to include non-promise values, you can wrap them in Promise.resolve()
to create a resolved promise.
-----------------------------------------------------
4.How does Promise.all differ from Promise.race?

Example Answer: Promise.all waits for all promises to fulfill or one to reject,
while Promise.race waits for the first promise to either fulfill or reject.
--------------------------------------------

################################################################Promise.race#######
################################################

1.Promise.race resolves or rejects as soon as the first promise in the iterable


settles,
it will log either the successful result or the error from the first settling
promise.
-------------------------------------------------------------------------
2.It also accepts array of promise.

Example:-
const promise1 = new Promise(resolve => setTimeout(() => resolve('Promise 1'),
1000));
const promise2 = new Promise((_, reject) => setTimeout(() => reject(new
Error('Promise 2 failed')), 500));
const promise3 = new Promise(resolve => setTimeout(() => resolve('Promise 3'),
1500));

Promise.race([promise1, promise2, promise3])


.then(result => console.log('First promise resolved:', result))
.catch(error => console.error('First promise rejected:', error.message));
-----------------------------------------------------------------------------------
-----------
3.Explain the purpose of Promise.race and when you might use it.

Example Answer: Promise.race is used when you want to race multiple asynchronous
tasks and handle the result or error from the first one that completes,
regardless of whether it's a success or failure.
-----------------------------------------------------------------------------------
-----
4.How does Promise.race differ from Promise.all?
Example Answer: Promise.race resolves or rejects as soon as the first promise
settles,
while Promise.all waits for all promises to fulfill or one to reject.
-----------------------------------------------------------------------------------
------
5.What happens if multiple promises in Promise.race settle at the same time?

Example Answer: Promise.race will take the result or error from the first promise
that settles,
so if multiple promises settle at the same time, the result or error from the first
one in the iterable will be used.

########################################################### asnyc/await
####################################

1.Explain the purpose of async/await and when you might use it.

Example Answer: async/await is used to simplify asynchronous code, making it more


readable and easier to reason about.
It is often used when working with promises to handle asynchronous operations in a
more synchronous-style manner.
-----------------------------------------------
2.What is the difference between async/await and using plain promises with .then()
and .catch()?

Example Answer: While both handle asynchronous code, async/await provides a more
synchronous-like syntax, making the code look similar to synchronous code.
It also simplifies error handling with the use of try...catch.
-------------------------------------------------------------------------
3.Can you use await outside of an async function?

Example Answer: No, await can only be used inside a function declared with the
async keyword. It is designed for use within asynchronous functions.
------------------------------------------------------------------------------

4.How does error handling work with async/await?

Example Answer: Errors can be handled using try...catch. If an asynchronous


operation within the try block throws an error, it will be caught in the catch
block.
--------------------------------------------------------------------------------
5.What happens if a promise is rejected inside an async function without error
handling?

Example Answer: If a promise is rejected inside an async function without proper


error handling, it will result in an unhandled promise rejection error.
It's essential to handle errors to avoid this.
--------------------------------------------------------------
6.How would you use Promise.all with async/await?

Example Answer: You can use Promise.all to concurrently execute multiple


asynchronous operations and await the result. For example, fetching data from
multiple APIs concurrently.

async function fetchDataConcurrently() {


const [data1, data2, data3] = await Promise.all([
fetchData('https://api.example.com/data1'),
fetchData('https://api.example.com/data2'),
]);

console.log('All data fetched:', data1, data2);


}

You might also like