Sitemap
codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript: Promises explained with simple real life analogies

3 min readNov 19, 2017

--

A promise being initiated. Photo by Ben White on Unsplash

Promise: In Layman terms

Promise: The definition

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object you attach callbacks to, instead of passing callbacks into a function.

Promise: In JavaScript

console.log("1");
setTimeout(function(){console.log("2");},3000);
console.log("3");
setTimeout(function(){console.log("4");},1000);
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…

if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(function(result) {
console.log("Promise worked");
}, function(err) {
console.log("Something broke");
});
Promise returned successfully. Photo by Scott Webb from Pexels

Promise: Example

Further reading

If this post was helpful, sign up for my JavaScript newsletter.

--

--

codeburst
codeburst

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Responses (9)