Jump to Categories

Promises

A promise represents the eventual result of an asynchronous operation.spring.io

Promises provide a simpler alternative for executing, composing, and managing asynchronous operations when compared to traditional callback-based approaches.

A promise can be one of three states:

  • Pending - the promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.
  • Fulfilled - the asynchronous operation has completed, and the promise has a value.
  • Rejected - the asynchronous operation failed, and the promise will never be fulfilled. In the rejected state, a promise has a reason that indicates why the operation failed.

Basic Example(s)

In the following example getSomeInfo() is an async function that returns a promise.

const info = getSomeInfo();

info.then(function (info) {
  console.log(info);
}, function (error) {
  console.error(error);
});

Making use of the then method to chain async operations.

const info = getSomeInfo();
info
  .then(callAnotherAsyncOp)
  .then(function (moreInfo) {
    console.log(moreInfo);
  }, function(error) {
    console.error(error);
  });

Example of making a promise

function makePromise(whatever) {
  return new Promise(function(resolve, reject) {
    if (whatever) {
      resolve(whatever);
    } else {
      reject(Error('Nothing passed'));
    }
  });
}

var prom = makePromise();
prom.then((msg) => {
  console.log(msg);
}).catch((err) => {
  console.log(err);
});

var keepsHisWord;
keepsHisWord = true;
promise1 = new Promise(function(resolve, reject) {
  if (keepsHisWord) {
    resolve("The man likes to keep his word");
  } else {
    reject("The man doesnt want to keep his word");
  }
});
console.log(promise1);

promise2 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve({
      message: "The man likes to keep his word",
      code: "aManKeepsHisWord"
    });
  }, 10 * 1000);
});
console.log(promise2);

Codepen Examples

See the Pen Promises by Shane Prendergast (@webknit) on CodePen.

Ajax promise

See the Pen Promise Ajax by Shane Prendergast (@webknit) on CodePen.

Callback hell

"Callback hell", a technique that makes use of nested functions to control the different outcomes of code.

getJSON('whatever.json', function(error, data) {
  if(error) console.log(error);
  else {
    doSomething(data, function(error, something) {
      if(error) console.log(error)
      else {
        doAnotherthing(something, function(error, whatever) {
          ................
        }
      }
   }
}

References