Scott Penrose

Promises

Scott is an expert software developer with over 30 years experience, specialising in education, automation and remote data.

Promises pattern from Callbacks...

Basic callback structure, where you can delay "next" as much as you need. However doing this with Promises is currently a mystery.

See also Promises for Async; Promises for Callbacks

#!JavaScript

 function getPerson(id, next) {
   next(null, "Person Number " + id);
 }

 getPerson(37, function(err, name) {
   console.log(name);
 });

Extend this to using a simple database query, where it takes time.

#!JavaScript

 function getPerson(id, next) {
   database.query("SELECT name FROM person WHERE id = ?", id)
   .then(function(data) {
     next(null, data.name);
  });
  // Also catch errors and next(err);
 }

 getPerson(37, function(err, name) {
   console.log(name);
 });

What happens now you can do more e.g.

#!JavaScript

 function getPerson(id, next) {
   database.query("SELECT name FROM person WHERE id = ?", id)
   .then(function(data) {
     if (!data || !data.name) {
        database.query("UPDATE person SET name=? WHERE id = ?", "Person X", id)
        .then(function(data) {
          next(null, data.name);
        });
     }
     else {
       next(null, data.name);
     }
  });
  // Also catch errors and next(err);
 }

 getPerson(37, function(err, name) {
   console.log(name);
 });