Javascript Promises

Javascript Promises

What is a Promise?

A promise is an object that has the potential to generate a single value in the future; either a resolved value or an explanation why it hasn't been resolved yet (a network error is a good example ).

In its simplest from, a promise is a result of an asynchronous operation. Note that a promise can have an eventual successful completion or failure.

The constructor syntax for a promise object is:

let promise = new Promise(function(resolve, reject) {
  // executor
});

The executor (in the above code snippet) is the function that is supplied to the new Promise. The executor starts automatically when a new Promise is created.

Take a look at this Scenario...

Suppose you decide (promise) to complete a course over a period of time. Meanwhile time is relative, as you may and may not finish within the specified time. If you finish the course over the period of time, then the promise is resolved. If not, the promise is rejected.

Let's put our thought process (scenario) into code...

let courseCompleted = true;

let learnCourse = new Promise(function (resolve, reject) {
    if (courseCompleted) {
        resolve("I have completed learning this course.");
    } else {
        reject("I haven't completed learning this course yet.");
    }
});

The above code snippet is a promise. A promise is simply the result of an asynchronous operation.

A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. - MDN

States of Javascript Promise

A promise has three common states, which are;

  1. Pending (not yet fulfilled or rejected) - This is the initial state of a promise call, at this point the promise is still in a process of call. It is neither fulfilled (successful) nor rejected (failed).

  2. Fulfilled - This means that the process or operation has been finished successfully. Here, the resolve() function is used. The activity relating to the promise was successful in this case.

  3. Rejected - A promise is rejected when an operation fails. With reference to our scenario above, the learnCourse function will fail if the time factor is not met. Here, you tried but the external circumstances (time) didn't work out as planned. The reject() function is called here.

Conclusion

There are a lot more to cover on Javascript promises, but this little blog post of mine can't extensively cover it all. I hope you definitely got something from this, thanks for your time.