Frontend Development: JavaScript

🚀 ReDI Fall 2020 🚀

Lecture 13

Promises

What we will do today

  • Organisational stuff
  • Your Questions
  • Quiz!
  • Synchronous and Asynchronous Code
  • Promises
  • A few examples

One-on-one lessons

Schedule available in Google Docs

Your Questions

Quiz

Synchronous vs Asynchronous

  • Synchronous operations are executed sequentially. Only once the first operation finished, the next operation can start
  • Asynchronous operations are executed in parallel. One operation may run, and the next operation may start before the first one finishes

Promises

  • Wrappers for asynchronous operations
  • They offer a way to wait for an asynchronous operation to finish

Construction of promises

  • Promise-constructor takes executer function
  • Executor function takes two arguments: "resolve" and "reject"
  • "resolve" is equivalent to a function's "return"
  • "reject" is used to signal that an operation failed
new Promise((resolve, reject) => { // asynchronous logic... resolve(/* return value of promise*/); });

Promise chain

  • You can associate further action to a promise once it finishes with then()
  • then() returns a Promise, meaning that you can chain multiple then() calls
new Promise((resolve) => { resolve(5); }) .then((returnValue) => returnValue * 2) .then((returnValue) => { console.log(returnValue); }); // Prints 10

Error handling

  • You can handle errors inside the Promise with catch()
  • Code in finally() is always executed, regardless of wether there was an error or not
new Promise((resolve) => { if (Math.random() > 0.5) { resolve(); } else { reject ('Random number was too small'); } }) .then(() => { console.log('No error'); }) .catch((error) => { console.log('Error: ' + error); }) .finally(() => { console.log('Promise is done'); }); // Prints 'No error' half of the time, // and 'Error: Random number was to small' the other half // Afterwards, it prints 'Promise is done'

Example: imageReady()

  • We build a Promise for HTML image elements
  • Resolves, once the image is loaded

Example: fetch()

  • Built-in promise for XMLHttpRequests
  • Resolves with the response, once the request is done