immediate promise resolve

Immediate Promise Resolve

Immediate Promise Resolve is a feature of JavaScript Promises that allows a Promise to be resolved immediately without waiting for any asynchronous operations to complete. This means that the Promise's callback function is executed immediately, rather than being queued up to execute later after any other pending Promises have been resolved.

One common use case for Immediate Promise Resolve is when a function needs to return a Promise that resolves with a specific value, without performing any asynchronous operations. In this case, the function can simply return a Promise that immediately resolves with the desired value.

Example:


function getUser() {
  return new Promise(resolve => {
    resolve({ name: "Raju", age: 25 });
  });
}

const userPromise = getUser();

userPromise.then(user => {
  console.log(user); // { name: "Raju", age: 25 }
});

In the above example, the getUser function returns a new Promise that immediately resolves with an object representing a user. The then method is then used to handle the resolved value of the Promise, logging the user object to the console.

Another way to achieve Immediate Promise Resolve is by using the Promise.resolve method. This method returns a new Promise that immediately resolves with the specified value.

Example:


const userPromise = Promise.resolve({ name: "Raju", age: 25 });

userPromise.then(user => {
  console.log(user); // { name: "Raju", age: 25 }
});

In this example, the Promise.resolve method is used to create a new Promise that immediately resolves with an object representing a user. The then method is then used to handle the resolved value of the Promise, logging the user object to the console.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe