DEV Community

Takaya Kobayashi
Takaya Kobayashi

Posted on • Edited on

7 1

JavaScript の async/await の仕様をずっと誤解していた

すごい初歩的なことかもしれないのだけれど、年単位ぐらいで誤解したままコードを書いていたので懺悔のためにも書いておく...。

何が違ったかというと、async function の扱いである。async function も function と同じだとおもっていて、 Promise を返さないと呼び出し側で await できないと勘違いしていた。そのため、今までは

const fn = () => new Promise(async (resolve, reject) => {...})
Enter fullscreen mode Exit fullscreen mode

というような感じで Promise を一旦返すようにしていた。しかし、async function は呼び出すと Promise を返してくれるのだ。

参照: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function

const fn = async () => {}

console.log(fn)
console.log(fn())
Enter fullscreen mode Exit fullscreen mode

Node.js v9.5 で確認した。

[AsyncFunction: fn]
Promise { undefined }
Enter fullscreen mode Exit fullscreen mode

Promise が返ってくる...。よくよく調べていくと async function の中で return すると Promiseresolve し、 throw すると Promisereject することになるんだそうな。

const fn = async () => {
  return 'yo'
}

const main = async () => {
  const res = await fn()
  console.log(res)
}

main()
Enter fullscreen mode Exit fullscreen mode

=>

yo
Enter fullscreen mode Exit fullscreen mode
const fn = async () => {
  throw new Error('err')
  return 'yo'
}

const main = async () => {
  try {
    const res = await fn()
    console.log(res)
  } catch (err) {
    console.log(err)
  }
}

main()
Enter fullscreen mode Exit fullscreen mode

=>

Error: err
Enter fullscreen mode Exit fullscreen mode

まじか...。俺の Promise とはなんだったんだ.........。とても恥ずかしい.....。

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay