Open In App

JavaScript Promise constructor

Last Updated : 08 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Creating an new promise and resolving geeks for geeks
const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('geeks for geeks');
    }, 100);
});
 
promise1.then((value) => {
    console.log(value);
    // output will be : geeks for geeks
});
 
// output will be : [object Promise]
console.log(promise1);


Output

Promise { <pending> }
geeks for geeks

 Example 2: In this code, we are going to create two promise constructors.

Javascript




// Creating first promise constructor
const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('geeks for geeks');
    }, 100);
});
 
 
////creating second promise constructor
const promise2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('computer science portal');
    }, 100);
});
 
promise2.then((value) => {
    console.log(value);
    // output: "computer science portal"
});
 
promise1.then((value) => {
    console.log(value);
    //  output: "geeks for geeks"
});
console.log(promise1);
    // output: [object Promise]


Output

Promise { <pending> }
geeks for geeks
computer science portal

Example 3: In this example, we will display a value.

Javascript




// Creating first promise constructor
const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('geeks for geeks');
    }, 100);
});
 
 
// Creating second promise constructor
const promise2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('computer science portal');
    }, 100);
});
 
promise2.then((value) => {
    console.log(value);
    // output: "computer science portal"
});
 
promise1.then((value) => {
    console.log(value);
    //  output: "geeks for geeks"
});
console.log(2 + 3);
    // output: [object Promise]


Output

5
geeks for geeks
computer science portal



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads