|
1 |
| -# Async Await |
| 1 | +### Async Await |
| 2 | + |
| 3 | +`async` and `await` is **syntactic sugar** for using `promises`. That means that the `async` and `await` keywords are transpiled to normal `promise` syntax. |
| 4 | + |
| 5 | +A simple example of usage of `async` and `await`: |
| 6 | + |
| 7 | +```JavaScript |
| 8 | +// A simple example: |
| 9 | +async function example(){ |
| 10 | + const aVariable = await aFunction(); |
| 11 | + console.log(aVariable) |
| 12 | +} |
| 13 | + |
| 14 | +example(); |
| 15 | +``` |
| 16 | + |
| 17 | +`async` is written before the function keyword when creating a new function, and enables the usage of the `await` keyword within the function. `await` is only used before function calls that return a promise. We can therefore directly see that `aFucntion` above will be run asynchronously, and return a promise. |
| 18 | + |
| 19 | +Let's say that `aFunction` returns a promise that resolves to the string `hello`. What happens when using the `Async / Await` keyword is: |
| 20 | + |
| 21 | +0. The function `example` is invoked. |
| 22 | +1. The function `aFunction`, which returns a `promise`, is executed asynchronously. |
| 23 | +1. The code waits for the promise returned by `aFunction` to resolve. |
| 24 | +1. When the `promise` is resolved, then `aVariable` is assigned whatever the `promise` is resolved to (`'hello'`). |
| 25 | +1. The `console.log` prints `hello` to the standard output. |
| 26 | + |
| 27 | +Let's remove the `Async / Await`. |
| 28 | + |
| 29 | +```JavaScript |
| 30 | +// A simple example: |
| 31 | +function example(){ |
| 32 | + const aVariable = aFunction(); |
| 33 | + console.log(aVariable) |
| 34 | +} |
| 35 | + |
| 36 | +example(); |
| 37 | +``` |
| 38 | + |
| 39 | +What happens in this example is: |
| 40 | + |
| 41 | +1. The function `aFunction`, which returns a `promise`, is executed asynchronously. |
| 42 | +2. `aVariable` is assigned the promise. |
| 43 | +3. The `console.log` prints `Promise { <state>: "pending" }`. |
| 44 | +4. The promise resolves to `'hello'`, but that `'hello'` is never handled. |
| 45 | + |
| 46 | +## Extended explanation |
| 47 | + |
| 48 | +```JavaScript |
| 49 | +async function getUsers(){ |
| 50 | + const response = await fetch('https://jsonplaceholder.typicode.com/users') |
| 51 | + const data = await response.json() |
| 52 | + console.log('THIS LOGS 10 USER FROM JSON PLACEHOLDER >>', data) |
| 53 | + return data |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +or as arrow function |
| 58 | + |
| 59 | +```JavaScript |
| 60 | +const getUsers = async () => { |
| 61 | + const response = await fetch('https://jsonplaceholder.typicode.com/users') |
| 62 | + const data = await response.json() |
| 63 | + console.log('THIS LOGS 10 USER FROM JSON PLACEHOLDER >>', data) |
| 64 | + return data |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +The two functions above can be written using the `Promise` syntax. It is then written as follows: |
| 69 | + |
| 70 | +```JavaScript |
| 71 | +function getUsers() { |
| 72 | + return new Promise(resolve => { |
| 73 | + fetch('https://jsonplaceholder.typicode.com/users') |
| 74 | + .then(response => { |
| 75 | + return response.json() |
| 76 | + }) |
| 77 | + .then(data => { |
| 78 | + console.log('THIS LOGS 10 USER FROM JSON PLACEHOLDER >>', data) |
| 79 | + resolve(data); |
| 80 | + }) |
| 81 | + }) |
| 82 | +} |
| 83 | +``` |
| 84 | + |
| 85 | +If you do not return anything from the `async function`, then the promise is simply resolved to `undefined`. |
| 86 | + |
| 87 | +When having `async/await` translated, we can see a two important things. |
| 88 | + |
| 89 | +1. An async function always returns a promise |
| 90 | +2. Async function does not have error handling |
| 91 | + |
| 92 | +```JavaScript |
| 93 | +console.log(getUsers() instanceof Promise) // true |
| 94 | +``` |
| 95 | + |
| 96 | +The error is best handled by using a `try/catch` statement inside the async function. **You can then either handle the error in the async function or throw an error and handle it outside the async function.** |
| 97 | + |
| 98 | +```JavaScript |
| 99 | +// Handle error inside of the async function |
| 100 | +async function getUsers () { |
| 101 | + try { |
| 102 | + const response = await fetch('https://jsonplaceholder.typicode.com/users') |
| 103 | + const data = await ressspondse.json() |
| 104 | + console.log('THIS LOGS 10 USER FROM JSON PLACEHOLDER >>', data) |
| 105 | + } catch (error) { |
| 106 | + console.log(error) // ReferenceError: "ressspondse is not defined" |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +getUsers() |
| 111 | + |
| 112 | +// Handle error outside the async function |
| 113 | +async function getUsers () { |
| 114 | + try { |
| 115 | + const response = await fetch('https://jsonplaceholder.typicode.com/users') |
| 116 | + const data = await ressspondse.json() |
| 117 | + console.log('THIS LOGS 10 USER FROM JSON PLACEHOLDER >>', data) |
| 118 | + } catch (error) { |
| 119 | + throw error; |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +getUsers().catch(error => { |
| 124 | + console.log(error) // ReferenceError: "ressspondse is not defined" |
| 125 | +}) |
| 126 | +``` |
0 commit comments