Skip to content
Related Articles

Related Articles

JavaScript Promise constructor
  • Last Updated : 08 Mar, 2021

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:

  • 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




<script>
// 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);
</script>

Output:

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

Javascript




<script>
// 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]
</script>

Output:

Example 3: Display a value

Javascript




<script>// 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]
</script>

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :