javascriptpromises



javascriptpromises

0 0


javascriptpromises


On Github stillesjo / javascriptpromises

Javascript Promises

And why they are awesome!

Why promises

Perform time consuming tasks

Fetch from database

Fetch from API

Callbacks

Callbacks

Function to be called once done

function readFromFileOrSomething(cb) {
  // Perform read operations
  cb(err);
}

Send errors or null to callback

readFromFileOrSomething(function(err) {
    if (err) {
      console.log('Uh oh!');
    }
})

Why callbacks suck!

Callback hell

Hell on earth

function deepFunction() {
   createPerson(function(employee) {
       createRestaurant(function(restaurant) {
           createEmployeeRegister(function(register) {
               register.addEmployee(employee, function() {
                   restaurant.addRegister(register, function() {
                       restaurant.notifySomeone(function() {
                           console.log('Done!');
                       });
                    });
                });
            });
        });
    });
}

Function arguments

// Looks harmless
function addEmployee(employee, restaurant, register, cb) {}

Add null

// Won't work!
addEmployee(employee, function() {})

// Works but looks like crap
addEmployee(employee, null, null, function(){ /* code here */});

Alternatives?

// Define cb first!
function addEmployee(cb, employee, restaurant, register) {}

// Provide cb-function first!
addEmployee(function() {
  // Do stuff
}, employee, null, null) // Not very readable

Error handling...

funcThatTakesCallback(function(err) {
  if (!err) {
    otherTaskThatTakesCallback(function(err) {
      if(!err) {
        console.log('Done!');
      } else {
        handleError();
      }
    });
  } else {
    handleError();
  }
});

Add error handling to the deepFunction() 😱

Promises

Part of ES6 (EcmaScript 2015)

Already implemented basically everywhere!

Javascript Promises And why they are awesome!