-
I seem to have forgotten a lot.
-
I should have understood Promise and async/await before, but I forgot.
-
Promise
- Reading it again, it’s actually a quite simple mechanism.
- Maybe because I understood it before.
- Complicated part
- Once caught, it changes from rejected to resolved.
- It’s like handling an error and saying “OK”.
- So if there is a
thenaftercatch, it will also be processed.
- Once caught, it changes from rejected to resolved.
- Promise - TypeScript Deep Dive Japanese version
-
The reason to use Promise is that you can handle errors in a synchronous way for asynchronous/callback-style code.
- I see.
-
If an error occurs, it jumps to the subsequent
catch(and skips the intermediatethen). -
Synchronous errors are also caught by the nearest subsequent
catch.
- Reading it again, it’s actually a quite simple mechanism.
-
Promise.then
- If you return
x, it returns a resolved promise object withxas the value.
- If you return
-
Promise.catch
-
Promise.all/race
- This is convenient.
- I remember struggling to implement this in Swift.
allis like AND,raceis like OR.
-
async
- A declaration that a function runs asynchronously on a separate thread.
asyncfunctions return a Promise object, so you can write something likeasync_func().then(~~).- The return value of an
asyncfunction comes back as a Promise Value.
- The return value of an
-
await
- It allows you to write in a flat manner at the same level because chaining with
.thencan be cumbersome. - It can only be used inside an
asyncfunction.- I guess it’s because it would be problematic if the main thread stops otherwise.
- It can also be used with top-level await (takker).
- Example
- Inside an ESModule
- Since the
script.jsof my page is loaded as an ESModule, it works even if you write it directly like this: js
- Since the
- Inside an ESModule
- Example
- It allows you to write in a flat manner at the same level because chaining with
const res = await fetch("something to load");
const text = await res.text();
// ... - [[Developer Console]]
- In environments where this is not available ([[Classic Script]] or [[Node.js]]), you can use `(async () => { /* ... */ })()` to wrap and use it.
Resources
- Promise, async/await
- Highly recommended because it’s very easy to understand (takker)(takker)(takker)
- Event loop: microtasks and macrotasks
- Read this when you want to understand how Promises work.
- Using Promises - JavaScript | MDN