DEV Community

Adam Hawley
Adam Hawley

Posted on • Originally published at adamjhawley.com

Get Started with JavaScript Promises (in Under 2 Minutes)

Intro

Welcome to an extremely brief introduction to JavaScript Promises. After getting to grips with Promises myself I thought I would share the essentials that I needed to put them into practice.


Basics of JS Promises

Promises can be defined with the following recipe:

function function1 () {
  return new Promise ((resolve, reject) => {
    try {
      doSomeStuff()
      resolve()
    } catch (err) {
      reject(err) 
    }
  })
}
Enter fullscreen mode Exit fullscreen mode

resolve() should be called if the operation associated with the Promise has been successful. reject() should be called if the Promise could not be resolved, maybe there was some sort of problem when trying to perform the associated operation.

The caller function then has the option to asynchronously wait for the Promise to resolve using await or the then() method of Promises. To use await, declare the entire function as asynchronous using the async keyword. Here are examples of both:

async function callerFunc1() {
  // Use 'await'
  await function1()
}

function callerFunc2() {
  // Use '.then()'
  function1().then(() => {
    doSomethingAfterwards() 
  })
}
Enter fullscreen mode Exit fullscreen mode

Two extra things about Promise.then(). Firstly, we can chain .then() statements together to make something that operates like so:

function callerFunc3() {
  function1.then(() => {
    console.log('First thing finished')
  }).then(() => {
    console.log('Second thing finished')
  })
}
Enter fullscreen mode Exit fullscreen mode

Secondly, then() can actually take two arguments: one in case the Promise resolves and another to handle the case when the Promise rejects.

function callerFunc4() {
  function1.then(() => {
    console.log('Everything went to plan!')
  }, () => {
    console.log('The Promise rejected :(')
  })
}
Enter fullscreen mode Exit fullscreen mode

If you want to see these examples in action, check out this StackBlitz


Conclusion

Hopefully you found this helpful, to get updates as soon as I release helpful guides such as this follow me on Twitter or Dev!

Top comments (0)