JavaScript Promises


"I Guarantee a Outcome!"

"Creating code" refers to code that may require a certain amount of time.

"Consuming code" refers to code that needs to pause and wait for a result.

A promise is like a connection between the code that creates something and the code that uses it.

JavaScript Promise Object

A promise includes the code that generates a result and the code that uses that result.

Promise Syntax

let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

When the code creating something gets the outcome, it needs to trigger one of the two callbacks:

WhenCall
SuccessmyResolve(result value)
ErrormyReject(error object)

Promise Object Properties

A JavaScript Promise object can have these qualities:

  • Pending
  • Fulfilled
  • Rejected

The Promise object has two properties: state and result.

When a Promise object is still in progress, the outcome is not yet defined.

When a Promise is successfully completed, it produces a specific value.

When a Promise is marked as "rejected," it means there is an error.

myPromise.statemyPromise.result
"pending"undefined
"fulfilled"a result value
"rejected"an error object

You're not allowed to view the Promise attributes state and result.

You need to utilize a Promise method for managing promises.


Promise How To

Here's how you can use a Promise:

myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

Promise.then() requires two inputs: one for handling success and another for managing failure.

You don't have to use both, just choose whether you want to add a callback for success or failure.


JavaScript Promise Examples

To show how promises work, we'll use the callback examples discussed in the previous chapter:

  • Anticipating a Delay
  • File is not ready yet.

Waiting for a Timeout


Waiting for a file