|
| 1 | ++++ |
| 2 | +title = "Async JavaScript" |
| 3 | +slug = "async-javascript" |
| 4 | +layout = "page.html" |
| 5 | +date = 2021-05-08 |
| 6 | +draft = true |
| 7 | +[taxonomies] |
| 8 | +tags = ["async", "javascript"] |
| 9 | ++++ |
| 10 | + |
| 11 | +There are 3 ways work with **asynchronous** code in JavaScript. |
| 12 | +- Callbacks |
| 13 | +- Promises (ES6; node v4.x, Chrome 32) |
| 14 | +- Async / Await (ES7; node v8.x, Chrome 55) |
| 15 | + |
| 16 | +Lets explore each of these for this example use case: |
| 17 | +```ts |
| 18 | +posts = [ |
| 19 | + { title: "Post 1", body: "This is post 1" }, |
| 20 | + { title: "Post 2", body: "This is post 2" } |
| 21 | +] |
| 22 | +``` |
| 23 | + |
| 24 | +Promises are immutable, the handler cannot be changed. We are also guaranteed to receive a return value: either what we intended or an error. |
| 25 | + |
| 26 | +https://blog.logrocket.com/the-perfect-architecture-flow-for-your-next-node-js-project/ |
| 27 | + |
| 28 | +- async - pushes the operation to run asynchronously |
| 29 | +- await - pause execution until myPromise is resolved |
| 30 | + |
| 31 | +## Callbacks |
| 32 | +--- |
| 33 | + |
| 34 | +Callbacks are unintuitive and hard to debug. |
| 35 | + |
| 36 | + |
| 37 | +## Promises |
| 38 | +--- |
| 39 | + |
| 40 | +A `Promise` is always fulfilled - either resolved or rejected. |
| 41 | +`Promise` is exclusively used in JS ecosystem: fetch API, axios, etc. So, it's a good idea to learn how to work with it properly. |
| 42 | + |
| 43 | +- A `Promise` enters a 'pending' state until it is resolved or rejected. |
| 44 | +- A promise can be created using `new Promise()` constructor |
| 45 | + |
| 46 | +```ts |
| 47 | +function createPost(post) { |
| 48 | + // create new promise |
| 49 | + new Promise((resolve, reject) => { |
| 50 | + setTimeout(() => { |
| 51 | + try { |
| 52 | + posts.push(post) |
| 53 | + resolve() |
| 54 | + } catch { |
| 55 | + reject("Error: Something went wrong") |
| 56 | + } |
| 57 | + }) |
| 58 | + }) |
| 59 | +} |
| 60 | +createPost({ title: "Post 3", body: "This is post 3" }) |
| 61 | + .then(() => console.log("added")) |
| 62 | + .catch(err => console.log(err)) |
| 63 | +``` |
| 64 | + |
| 65 | +- `Promise.all` |
| 66 | + |
| 67 | +Most of the time, we'll be dealing with returned promises from these external packages. |
| 68 | + |
| 69 | +```ts |
| 70 | +const promise1 = Promise.resolve('Hello world!') |
| 71 | +const promise2 = 10 |
| 72 | +const promise3 = new Promise((resolve, reject) => { |
| 73 | + setTimeout(resolve, 2000, 'Goodbye') |
| 74 | +}) |
| 75 | +// need to resolve 2 promises; format to JSON -> use data |
| 76 | +const promise4 = fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()) |
| 77 | + |
| 78 | +// values = an array of resolved promises |
| 79 | +Promise.all([promise1, promise2, promise3, promise4]).then(values => console.log(values)) |
| 80 | +``` |
| 81 | + |
| 82 | +## Async / Await |
| 83 | +--- |
| 84 | + |
| 85 | +**Await** - waits for an asynchronous process to complete. |
| 86 | + |
| 87 | +NOTE: Async/Await do NOT invoke a seperate thread in the OS. |
| 88 | +<!-- Ref: <https://blog.stephencleary.com/2013/11/there-is-no-thread.html> --> |
| 89 | + |
0 commit comments