JavaScript Promise constructor
Last Updated :
08 Aug, 2023
JavaScript Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.
Promise constructor in JavaScript is mainly used to wrap functions that do not already support promises.
Syntax:
new Promise(executor)
Parameters: The promise constructor contains a single parameter:
- executor: The executor can be the custom code that ties an outcome to a promise. You, the programmer, write the executor.
Return Value: Another promise object, in which case the promise gets dynamically inserted into the chain.
Example 1: Creating only one promise constructor.
Javascript
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve( 'geeks for geeks' );
}, 100);
});
promise1.then((value) => {
console.log(value);
});
console.log(promise1);
|
Output
Promise { <pending> }
geeks for geeks
Example 2: In this code, we are going to create two promise constructors.
Javascript
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve( 'geeks for geeks' );
}, 100);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve( 'computer science portal' );
}, 100);
});
promise2.then((value) => {
console.log(value);
});
promise1.then((value) => {
console.log(value);
});
console.log(promise1);
|
Output
Promise { <pending> }
geeks for geeks
computer science portal
Example 3: In this example, we will display a value.
Javascript
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve( 'geeks for geeks' );
}, 100);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve( 'computer science portal' );
}, 100);
});
promise2.then((value) => {
console.log(value);
});
promise1.then((value) => {
console.log(value);
});
console.log(2 + 3);
|
Output
5
geeks for geeks
computer science portal
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...