Promise: The definition
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.
Let us first talk about JavaScript and its concurrency. JavaScript is single-threaded. Everything happens in the sequence it is written, line-by-line. But, asynchronous operations occur in the order they complete.
What do you think is logged in the console in the following example?
Now, let’s look at how you create a promise in JavaScript:
promise.then(function(result) {
console.log("Promise worked");
}, function(err) {
console.log("Something broke");
});
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"));
}
});
The output will be
1 3 4 2 . You may wonder why 4 is logged before 2. The reason for that is that even though line 2started executing before line 4 , it did not start executing for 3000ms and hence 4 is logged before 2 .console.log("1"); setTimeout(function(){console.log("2");},3000); console.log("3"); setTimeout(function(){console.log("4");},1000);
Comments
Post a Comment