Web Applications

Lab 10

Promise

  • Represents the eventual completion or failure of an asynchronous operation
  • Handlers for successful fulfillment and rejection can be added with then() and catch()
  • Can be chained

doSomethingAsynchronouslyAndReuturnPromise()
  .then(result => transformTheResult(result))
  .then(function callMeWhenReady(finalResult) {
    console.log("Got the final result: " + finalResult);
  })
  .catch(failureCallback);
      


const promise = new Promise((resolve, reject) => {
  resolve("value")
});

promise.then((result) => console.log(result));
      


const promise = Promise.resolve("value");
promise.then((result) => console.log(result));
      

Async / Await


function fetchData(url) {     
  fetch(url)
    .then(response => response.json())
    .then(data => console.log("Got the data: " + data))
    .catch(console.log("Can't fetch data");
}  
      


async function fetchData() {      
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log("Got the data:", data);
  } catch(error) {
    console.log("Can't fetch data")
  }
}
      


async function fetchData() {      
  try {
    const data = await(await fetch(url)).json();
    console.log("Got the data:", data);
  } catch(error) {
    console.log("Can't fetch data")
  }
}
      

Exercise 1

Exercise - Model

Download this page and resolve all TODOs.

Exercise 2

Render table

Download this page and resolve all TODOs.

AJAX

  • Asynchronous HTTP requests to the server without reloading page
  • Requests on background ~ event-driven
  • Typically exchanging JSON data, but can be other types (text, HTML, binary, ...)
  • GET, POST, DElETE, PUT, ...

Sending data

  • Encode data in URL
  • Send POST request with encoded data
  • Send JSON in request body and parse it on the server side
  • FormData

Cross-Origin Requests

Cross-origin network access

access-control-allow-methods: GET, OPTIONS
access-control-allow-origin: *
Cross-origin resource sharing (CORS) is the SELinux of the Web. You really want to do the right thing but it only works when you: "Access-Control-Allow-Origin", "*"

Exercise 3

Render table with NKOD

Download this page and resolve all TODOs.

The end…

Questions?

Feedback