Jump to Categories

Promises

Basic Example


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);
});

Simple Promise

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

Ajax promise

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

Callback hell

Promises are to help prevent "callback hell", a technique that makes use of nested functions to control the different outcomes of code. A promise achieves exactly the same thing as multiple callbacks, but it makes code easier to read and write.

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