JavaScript/Notes/Promises

From Noisebridge Wiki
Jump to navigation Jump to search

Promises are a new addition to ECMAScript. See: http://www.html5rocks.com/en/tutorials/es6/promises/ https://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-objects

Example with no Promise[edit]

var img = new Image();

var rejectTimer = setTimeout( function() {
  reject(Error("It broke"));
}, 4 * 1000);

img.onload = function() {
	clearTimeout(rejectTimer);
	resolve("Stuff worked!");
};

img.src = "https://www.google.com/images/srpr/logo11w.png?res";

function resolve(msg) { 
 	console.log(msg);
} 
function reject(err) {
  console.error(err);
};

Example with Promise[edit]

var promise = new Promise(function(resolve, reject) {
  var img = new Image();

  
  var rejectTimer = setTimeout( function() {
    reject(Error("It broke"));
  }, 4 * 1000);

  img.onload = function() {
  	clearTimeout(rejectTimer);
  	resolve("Stuff worked!");
  }
  img.src = "https://www.google.com/images/srpr/logo11w.png?sss";

});

promise.then(
 function(msg) { 
 	console.log(msg);
 }, 
 function(err) {
    console.error(err);
});