Promise in Js
Promise in Js
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.
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.
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?
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.
-----------------------------------------------------------------------------------
--------
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');
});
-----------------------------------------------------------------------------------
Since javascript is a single threaded... Means the task are executed one after
another snychronsly.
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.
---------------------------------------------
15.Explain async/await and how it relates to Promises.
promiseInput(1000).then((result) => {
console.log(result);
});
------------------------------------------------
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 urls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
];
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: 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#######
################################################
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));
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: 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.
------------------------------------------------------------------------------