Promises: A complete explanation of modern JavaScript

Promises: A complete explanation of modern JavaScript

JavaScript Promises: Allow us to first discuss JavaScript and its concurrency. JavaScript is single-threaded. It means all the things happen in a sequence as it's written, line-by-line. What do you think the results of the following example:

console.log("I am first");
setTimeout(function(){console.log("I am second");},3000);
console.log("I am third");
setTimeout(function(){console.log("I am fourth");},1000);

Your expected answer: 

  1. I am first
  2. I am second
  3. I am third
  4. I am fourth

But actual answer: 

  1. I am first
  2. I am third
  3. I am fourth
  4. I am second

The explanation above example without Promises:

Actually, 1st executed immediately. But the 2nd line has to wait for 3 seconds. So, 3rd line executed after 1st line. 4th line follow this sequence because it has to wait for 1 second. At the end 2nd line executed.

In a web app, You could use multiple asynchronous tasks and any if any task depends on early executed task's response, then you could get unexpected results.

Check this link:  Promise Vs Callback function in Javascript

A promise is a javascript object, represents a value may not available but will be available at some point in the future. It wraps an async task and notifies when it's completed. If you use the promise API for an asynchronous call to a remote web service. You will create a javascript object of promise that holds the data available in the future.

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

This constructor has an argument, is a callback with two parameters i.e. resolve and reject.
When you perform any async task successfully then call resolve otherwise call reject.

promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"

Now promise object has data. It may be resolved data or rejected data.

Check the following demo for a better explanation.

See the Pen An Overview of JavaScript Promises