JavaScript Promises - What You Need To Know

The four functions you need to know

  1. new Promise(fn)

    • fn takes two arguments: resolve and reject
    • resolve and reject are both functions which can be called with one argument
    • Returned promise will be rejected if an exception is thrown in the passed in function
  2. promise.then(onResolve, onReject)

    • Returns a promise
    • Returned promise resolves to value returned from handler
    • Chain by returning a promise from onResolve or onReject
    • Returned promise will be rejected if an exception is thrown in a handler
    • Use `Promise.reject` to return a rejected promise from onReject
    • Make sure to follow by promise.catch
  3. promise.catch(onReject)

    • Returns a promise
    • Equivalent to promise.then(null, onReject)
  4. Promise.all([promise1, promise2, ...])

    • Returns a promise
    • When all arguments resolve, returned promise resolves to an array of all results
    • When any arguments are rejected, returned promise is immediately rejected with the same value
    • Useful for managing doing multiple things concurrently

Packages

Extra Reading