Writing Javascript Promises

Building a Promise

So if you read my previous article we learned what promises are and how to work with them when functions like fetch and Axios return them to us. In this article, I’ll show you how to write your own promise.

Why Write Promises

Basically, if all the following questions get a yes response, you should write a promise.

  • I don’t want the rest of my code to sit and wait for that something else to finish

Writing a basic promise

const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if (true) {
resolve("The Promise has resolved")
} else {
reject("your promise has failed")
}, 3000)
.then(value => console.log(value))
.catch(err => console.log(err))
.finally (()=>console.log("Either Way I happen"))
  1. We assign a new Promise to the variables
  2. The Promise constructor is passed a function
  3. The promise function is always passed resolve/reject (I sometimes name them done/fail), which are functions to determine when the promise ends.
  4. setTimeout is set to run a function in 3 seconds (3000 milliseconds)
  5. At the end of timeout an if the statement is evaluated
  6. If evaluates true the resolve function invokes sending a string value as the value of the promise, this would then allow any .then calls on this promise to execute
  7. If evaluates false, the reject function invokes passing an error message which causes any .catch calls on this promise to get the error and execute
  8. Whether the promise succeeds or fails, any .finally calls will be executed

Things to keep in mind

  • .then calls return a promise, so they can return a value which gets passed to any .then calls chained to that .then. (promise.then().then().then())
  • Technically your code is still synchronous (a single process), what promises do is just allow the event loop to continue as an event loop it’ll evaluate the status of the promise on each loop. If the status is pending, the loop just continues executing other code, if resolved .then calls will then be executed, if reject then .catch calls will be executed.
  • Typically under the hood of things like fetch and mongoose are event emitters that emit events when http connections are made or streams are running, and it’s these events that may tell the promise to be resolved. Read my article on javascript events: https://tuts.alexmercedcoder.com/jsevents/



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
Alex Merced Coder

Alex Merced Coder

Alex Merced is a Developer Advocate for Dremio and host of the Web Dev 101 and Datanation Podcasts.