• Asynchronous processing in Javascript

  • 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 after catch, it will also be processed.
    • 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 intermediate then).

    • Synchronous errors are also caught by the nearest subsequent catch.

  • Promise.then

    • If you return x, it returns a resolved promise object with x as the value.
  • 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 like async_func().then(~~).
      • The return value of an async function comes back as a Promise Value.
  • 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
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