Sistemas y Tecnologías Web: Servidor

Master de II. ULL. 1er cuatrimestre


Organization ULL-MII-SYTWS-2122   Classroom ULL-MII-SYTWS-2122   Campus Virtual SYTWS   Chat Chat   Profesor Casiano

Async-Await

Read chapter Async/Await of the https://javascript.info book and make a report using the GitHub Classroom assigned repo. Solve the exercises.

Exercise 1: MicroTask and MacroTask Queues

Answer this question before running the program.

What is the output of this program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
setTimeout(function () {
    console.log('macrotask 1');
}, 0);

Promise.resolve().then(function () {
    console.log('microtask 1');
    setTimeout(function () {
        console.log('macrotask 2');
        Promise.resolve().then(
            () => console.log('Nested microtask 3')
        )
    }, 0);
}).then(function () {
    console.log('microtask 2');
});

Explain the changes in the stack, the running environment, the macrotask queue and the microtask queue. Make pictures of the way the callbacks and handlers go and leave the queues. Take screenshots of them and upload them to the assignment repo

  • Code at: campus-virtual/2021/sytws2021/apuntes/tema2-async/event-loop/exercises/promises/microtask-queue/promise-job-queue-2.js

Exercise 2: MicroTask and MacroTask Queues

The following example is taken from a stackoverflow question

Don’t look at the debate yet. Also, try to answer this question before running the code.

What is the output of this program?

1
2
3
4
5
6
7
8
9
10
11
// See https://stackoverflow.com/questions/51793906/settimeout-promise-resolve-macrotask-vs-microtask
for (let i = 0; i < 2; i++) {
	setTimeout(() => {
		console.log("Timeout ", i);
		Promise.resolve().then(() => {
			console.log("Promise 1 ", i);
		}).then(() => {
			console.log("Promise 2 ", i);
		});
	})
}

Explain the changes in the stack, the running environment, the macrotask queue and the microtask queue. Make pictures of the way the callbacks and handlers go and leave the queues. Take screenshots of them and upload them to the assignment repo

  • Solution at: tema2-async/event-loop/exercises/promises/async-await/stackoverflow-promise-resolve-and-queues.js

Rewrite a fetch using async/await instead of promises

Rewrite this example code from the Javascript.info book using async/await instead of .then/catch:

1
2
3
4
5
6
7
8
9
10
11
12
function loadJson(url) {
  return fetch(url)
    .then(response => {
      if (response.status == 200) {
        return response.json();
      } else {
        throw new Error(response.status);
      }
    });
}

loadJson('no-such-user.json').catch(console.log); // Error: 404
  • Solution at campus-virtual/2021/sytws2021/apuntes/tema2-async/event-loop/exercises/promises/async-await/solution-2-rewrite-loadjson-using-async-await.html

Simplify a more complex example with async/await

Below you can find another exercise from the book javascript.info.

Rewrite it using async/await instead of .then/catch and get rid of the recursion in favour of a loop in demoGithubUser: with async/await.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class HttpError extends Error {
  constructor(response) {
    super(`${response.status} for ${response.url}`);
    this.name = 'HttpError';
    this.response = response;
  }
}

function loadJson(url) {
  return fetch(url)
    .then(response => {
      if (response.status == 200) {
        return response.json();
      } else {
        throw new HttpError(response);
      }
    });
}

// Ask for a user name until github returns a valid user
function demoGithubUser() {
  let name = prompt("Enter a name?", "iliakan");

  return loadJson(`https://api.github.com/users/${name}`)
    .then(user => {
      alert(`Full name: ${user.name}.`);
      return user;
    })
    .catch(err => {
      if (err instanceof HttpError && err.response.status == 404) {
        alert("No such user, please reenter.");
        return demoGithubUser();
      } else {
        throw err;
      }
    });
}

demoGithubUser();
  • See Section Custom errors, extending Error. It is worth to read the full chapter Error Handling
  • See The Error Class at MDN: The constructor
  • The GitHub API doc for the end-point to get the public info for an user is here GitHub API REST Docs: Get a User. Here are several examples of how to get the info:

    1
    
    gh api /users/crguezl | jq .name
    

    or with curl

    1
    2
    3
    
     curl \
    -H "Accept: application/vnd.github.v3+json" \
    https://api.github.com/users/crguezl
    

    or using the @octokit/coremodule:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    const { Octokit } = require("@octokit/core");
    
    const octokit = new Octokit({ 
      // auth: `personal-access-token123` 
    });
    
    async function getUsername(name) {
      return await octokit.request('GET /users/{username}', {
        username: name
      })
    }
    
    getUsername('crguezl').then(r => console.log(r.data.name));
    

    when we run it:

    1
    2
    3
    4
    5
    6
    
    ➜  hello-octokit git:(master) pwd
    /Users/casianorodriguezleon/campus-virtual/2021/learning/octokit-learning/hello-octokit
    ➜  hello-octokit git:(master) node --version         
    v14.4.0
    ➜  hello-octokit git:(master) node octokit-example.js
    Casiano Rodriguez-Leon
    
  • Solution at /campus-virtual/2021/sytws2021/apuntes/tema2-async/event-loop/exercises/promises/async-await/solution-more-complex-example.html

Call async from non-async

Here is another exercise from the JavaScript.Info book. As the book says, it is a task that solves a quite common for developers new to async/await.

We have a “regular” function called f. How can you call the async function wait() and use its result inside of f?

Give at least two solutions.

1
2
3
4
5
6
7
8
9
10
11
async function wait() {
  await new Promise(resolve => setTimeout(resolve, 1000));

  return 10;
}

function f() {
  // ...what should you write here?
  // we need to call async wait() and wait to get 10
  // remember, we can't use "await"
}
  • Solution at tema2-async/event-loop/exercises/promises/async-await/solution-call-async-from-nonasync.html

See

Comment with GitHub Utterances