JS Promises

Questions?

What are promises?

Promises help us manage asynchronous operations (mainly server requests).

They provide a simple model to represent…

  • different states (e.g. a successful response)
  • and their "followup actions" (e.g. handling the successful response).

An example

getAllTitles()

.then(allTitles => {...})

.catch(error => {...})

success!

failure!

📞 function call

🕑

✔️ settled

returns a promise

.finally(...)

Promise libraries

Where do we use promises?

In all of our frontend projects, of course (webapp, cms, business dashboard, audience builder, memento, …)!

  • in combination with Angular's $resource
  • resolves for states and modals
  • pressing save buttons and waiting for something to happen
     

Promise functions overview

.resolve(value)

.reject(error)

.all([...])

.race([...])

 

.then(value)

.catch(error)

.finally(result)

returns a "successful" promise result

returns a "failed" promise result

resolves when all promises are finished

resolves when any promise is finished

 

handle the sucessful result

handle the failed result

do something when the promise finished
(not availabe in ES6 Promises)

Common pitfalls 🤞

  • nesting promises instead of using promise chaining
  • loading too many things at a time (e.g. when some things could be loaded on demand when opening a certain tab or modal)
  • not using $resource's placeholders (e.g. /:method)
  • doing too many things in one function

ES6 supports promises natively!

const myPromise = new Promise(function(resolve, reject) {
    // Do an async task async task and then...
    if (/* good condition */) {
	resolve('Success!');
    }
    else {
	reject('Failure!');
    }
});

myPromise.then(function(result) { 
    /* Do something with the result. */
}).catch(function(error) {
    /* Handle the error, e.g. show a message to the 
       user or log it to the backend, … */
});

… and browser coverage is quite good.

Promise alternatives (aka the future)

async function getTitles() {
    return fetch('https://apis.justwatch.com/content/titles/en_US/popular');
}

const titles = await getTitles();
console.log(titles);
// or getTitles().then(...);

Promise alternatives (aka the future)

Thank you. ❤️

Here are some helpful resources:

Promises in JavaScript

By Sebastian Herrmann

Promises in JavaScript

Introduction to promises and how we're using them.

  • 1,713