JavaScript/Notes/Promises

From Noisebridge
Jump to: navigation, 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

[edit] Example with no Promise

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

[edit] Example with Promise

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