DEV Community

Cover image for Javascript Promises
JCorley44
JCorley44

Posted on

Javascript Promises

A promise is an object that can potentially turn into a value in the future. The value will either be resolved or unresolved and if it does resolve it will be either resolved, rejected or pending. A better example of this would be to conceptually think of a promise in javascript just like a promise you might make to someone in real life. When you make that promise it will either be unresolved or resolved. While waiting for the promise to be fulfilled it has three stages of existence as mentioned previously: resolved, rejected or pending.

Stages of a Promise

Resolve: the promise will have a value
Reject: the promise has failed
Pending: the stasis period of waiting for the promise to receive either of the two previously mentioned states.

Example of a Promise

 let firstPromise = new Promise(function(resolve, reject) {
  setTimeout(function() {
      resolve('I will only eat one cookie');
  }, 2000);
});

firstPromise.then(function(data) {
  console.log(data); //will log 'I will only eat one cookie' after two seconds
});

Promises have become the standard way to deal with asynchronous code. Asynchronous coding models let multiple code blocks execute at the same time. It allows for new actions to start while the program is being ran. In the example the firstPromise is using resolve to fulfill the promise. After we use the then function to bind a callback so we can use the data from the resolve function. It is possible to bind multiple callbacks too!

var indecisivePromise = new Promise(function(resolve, reject) {
  setTimeout(function() {
      resolve('I will only eat one cookie');
  }, 2000);
});

indecisivePromise.then(function(data) {
  console.log(data + ' hopefully.');
});

indecisivePromise.then(function(data) {
  console.log(data + ' maybe.');
});

indecisivePromise.then(function(data) {
  console.log(data + ' I make no promises.');
});

Promises can only be resolved once. The method then can be chained but there can only be one resolve. Just like in real life once a promise has been fulfilled you can not fulfill the same promise for a second time unless you have another condition to the promise. That's why the then method is useful. IT

let multiResolvePromise = new 

Promise(function(resolve, reject) {

  setTimeout(function() {

//only this will revolve
      resolve('first resolve');

//the promise ends after the first resolve
      resolve('second resolve');
      resolve('third resolve');
      resolve('fourth resolve');
  }, 1000);
});


multiResolvePromise.then(function success(data) {
  console.log(data); //will print 'first resolve'
});

What happens if the promise is not fulfilled? The catch method allows us to have an output if the promise fails.

const failedPromise = new Promise((resolve, reject) => {

  let numberOfCookies = 1000000;

  if (numberOfCookies < 1) {
    resolve('Good job you only at one cookie!')
  } else {
    reject('I knew you would eat more than one, but one million that is madness.')
  }
});

failedPromise.then((resolveData) => {
  console.log(resolveData)
}).catch((rejectData) => {
  console.log(rejectData)
});

Since the conditional statement above is false the promise fails so the resolve method will not trigger thus leaving the promise unfulfilled.

Conclusion

Promises allow for coding asynchronously to be easier to understand and avoid using more complicated programming strategies. Promises will either resolve or reject depending on the criteria of the promise object. Once the promise is pending we can then chain then and catch to implement more intuitive asynchronous code instead of venturing into a "callback hell". If we were to use a lot of callbacks the code would be extremely hard to follow and become unruly making errors and debugging much harder to do.

Top comments (0)