promise with return value code example

Example 1: javascript return promise

function doSomething() {
  return new Promise((resolve, reject) => {
    console.log("It is done.");
    // Succeed half of the time.
    if (Math.random() > .5) {
      resolve("SUCCESS")
    } else {
      reject("FAILURE")
    }
  })
}

const promise = doSomething(); 
promise.then(successCallback, failureCallback);

Example 2: javascript promise

var promise = new Promise(function(resolve, reject) {
  // do some long running async thing…
  
  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//usage
promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

Example 3: resolve vs return promise js

In simple terms, inside a then handler function:

A) When x is a value (number, string, etc):
	- return x is equivalent to return Promise.resolve(x)
	- throw x is equivalent to return Promise.reject(x)

B) When x is a Promise that is already settled (not 
pending anymore):
	- return x is equivalent to return Promise.resolve(x), 
      if the Promise was already resolved.
	- return x is equivalent to return Promise.reject(x), 
      if the Promise was already rejected.
      
C) When x is a Promise that is pending:
	- return x will return a pending Promise, and it will 
    be evaluated on the subsequent then.
Read more on this topic on the Promise.prototype.then() docs.

Tags:

Misc Example