A land of Promises

ECMAScript 2015 came with a natively Promise.

The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never.

They eliminate some problems related with callbacks and allow us to write asynchronous code that looks and feels much like synchronous.

A Promise has 3 states:

  • pending: initial state, not fulfilled neither rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation has failed.

Bellow I’ll be showing examples of Promises in a Google Chrome extension I’ve developed a few months ago. I’ve used Promises because chrome.storage.local.get() is async and therefore I wanted to make sure that my data was fetched from storage when I needed it. You can find more about the project here.

Declaring a new Promise
replacements = new Promise(function (resolve, reject) {
chrome.storage.local.get("words", function (items) {
resolve(items);
});
});
Using the Promise object
replacements.then(function (replacements) {
if(replacements.words) {
replacements.words.forEach(function (replacement) {
var matchedText = v.textContent.match(new RegExp(replacement, “i”));

if (matchedText) {
// Use `` instead of ‘’ or “” if you want to use ${variable} inside a string
// For more information visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
highlightColor.then(function (item) {
var color = (item.color.startsWith(“#”)) ? item.color : “#” + item.color ;
var replacedText = node.innerHTML.replace(new RegExp(`(${replacement})`, “i”), `<span style=”background-color: ${color}”>$1</span>`);
node.innerHTML = replacedText;
});
}
});
}
}).catch(function (reason) {
console.log(“Handle rejected promise (“ + reason + “) here.”);
});

The code above is only executed when the Promise is resolved because I need the stored words in order to successfully execute the function and modify the DOM.

As you can see Promises are not difficult to understand and will allow you to develop better software and run away from the so called CallbackHell.