Basics about Promise-JavaScript.

fetch("string representing a URL to a data source")
.then(function(response) {return response.json();
})
.then(function(json){ // data of `json` to be able to manipulate DOM
})
let promise = new Promise(function(resolve, reject){
//do something
});
let promise = new Promise(function(resolve, reject) {
const x = "Hello Promise";
const y = "Hello Mr. Promise"
if(x === y) {
resolve();
} else {
reject();
}
});
  1. then()
  • .then() is invoked when a Promise is either resolved or rejected.
  • .then() method takes two functions as parameters.
  • .catch() is invoked when a promise is either rejected or some error has occurred in execution.
  • .catch() method takes one function as a parameter.
  • .catch() is just a shorthand for .then(null, errorHandler) )
promise
.then(function () {
console.log('Success!');
})
.catch(function () {
console.log('Some error has occured');
});
promise
.then(function () {
console.log('Success!');
})
.catch(function () {
console.log('Some error has occured');
});
.then(() => {
console.log('Do this, no matter what happened before');
});
// Bad example!

doSomething()
.then(function(result) {
doSomethingElse(result) // Forgot to return promise from inner //chain + unnecessary nesting
.then(newResult => doThirdThing(newResult));
})
.then(() => doFourthThing());
// Forgot to terminate chain with a catch!
  1. Not properly chain things together. This happens when we create a new promise but forget to return it. As a consequence, the chain is broken, or we have two independent chains racing. This means doFourthThing() won't wait for doSomethingElse() or doThirdThing() to finish, and will run in parallel with them, likely unintended. Separate chains also have separate error handling, leading to uncaught errors.
  2. Unnecessarily nests, enabling the first mistake. Nesting also limits the scope of inner error handlers, which — if unintended — can lead to uncaught errors. A variant of this is the promise constructor anti-pattern, which combines nesting with redundant use of the promise constructor to wrap code that already uses promises.
  3. Forgetting to terminate chains with catch. Unterminated promise chains lead to uncaught promise rejections in most browsers.
doSomething()
.then(function(result) {
return doSomethingElse(result);
})
.then(newResult => doThirdThing(newResult))
.then(() => doFourthThing())
.catch(error => console.error(error));
  • Improves Code Readability
  • Better handling of asynchronous operations
  • Better flow of control definition in asynchronous logic
  • Better Error Handling.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store