-
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
then
aftercatch
, 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 withx
as the value.
- If you return
-
Promise.catch
-
Promise.all/race
- This is convenient.
- I remember struggling to implement this in Swift.
all
is like AND,race
is like OR.
-
async
- A declaration that a function runs asynchronously on a separate thread.
async
functions return a Promise object, so you can write something likeasync_func().then(~~)
.- The return value of an
async
function 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
.then
can be cumbersome. - It can only be used inside an
async
function.- 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.js
of 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