JavaScript — Asynchronous Operations: Promises

Keerthana
1 min readApr 14, 2022

--

An article for Mid level Developers to act as Promises syntax refresher
This is part of a series “JavaScript — Asynchronous Operations”

Series “JavaScript — Asynchronous Operations”

Promise — A promise represents an operation that hasn’t completed yet.

A Promise is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: successfully ->
promise.then()
- rejected: failed ->
promise.catch()

A pending promise can go to either resolved (fulfilled with a value) or rejected (error with a reason) state.
The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.
working example here

Example:

The function passed to new Promise runs automatically when the new Promise is created. It should contain the code to be executed upon completion of asynchronous operations.

function makeBackendCall(bool) {
return new Promise((resolve, reject) => {
if (bool) {
resolve('output');
} else {
reject(new Error('error'));
}
});
}
makeBackendCall(true)
.then(value => {
console.log(value);
})
.catch(err => {
console.log(err);
});

Other Topics in this Series

JavaScript — Asynchronous Operations

5 stories

Callback functions
Promises
Async / Await
Making multiple Async Calls
- Callback Hell
- Promise Chain
- Async / Await with promises
Promise.all

--

--

No responses yet

Write a response