You are on page 1of 11

JavaScript

Introduction to Promises
What is Promise?

Promise is a self explanatory term, promise is to say definitely that you will do or not do something or
that something will happen .
A promise is an object that may produce a single value some time in the future: either a resolved value,
or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible
states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or
the reason for rejection.
A promise is an object which can be returned synchronously from an asynchronous function. It will be in
one of 3 possible states:
● Pending: The promise has neither resolved nor rejected (yet), the promise is still pending.
● Fulfilled: The promise has been resolved. Everything went fine, no errors occurred within the
promise
● Rejected: The promise has been rejected. Argh, something went wrong.
A promise is settled if it’s not pending (it has been resolved or rejected). Sometimes people use resolved
and settled to mean the same thing: not pending.
Chaining Promises

A promise can be returned to another promise, creating a chain of promises.

A great example of chaining promises is the Fetch API, which we can use to get a resource and
queue a chain of promises to execute when the resource is fetched.

The Fetch API is a promise-based mechanism, and calling fetch() is equivalent to defining our
own promise using new Promise().

The result of the .then itself is a promise value. This means that we can chain as many .thens as
we want: the result of the previous then callback will be passed as an argument to the next then
callback!
Async / Await

ES7 introduced a new way to add async behavior in JavaScript and make working with promises easier!
With the introduction of the async and await keywords, we can create async functions which implicitly
return a promise.

Although the fact that async functions implicitly return promises is pretty great, the real power of async
functions can be seen when using the await keyword! With the await keyword, we can suspend the
asynchronous function while we wait for the awaited value return a resolved promise. If we want to get
the value of this resolved promise, like we previously did with the then() callback, we can assign
variables to the awaited promise value!
Applications

● Promises are used for asynchronous handling of events.


● Promises are used to handle asynchronous http requests.

You might also like