Skip to content

awaitページのサンプルコードに誤りがあるかもしれません(resolveが呼び出されていない) #1129

Description

@Hideka-I

https://github.com/yytypescript/book/edit/master/docs/reference/asynchronous/await.md

気になった点

https://typescriptbook.jp/reference/asynchronous/await の「Promiseを直接awaitする」セクションのサンプルコードについて、気になる点があったので報告させていただきます。

現在のコード

async function main() {
  // 1秒後に値を返す
  await new Promise((resolve) => {
    setTimeout(() => resolve, 1000);
  });
}

気になる点

setTimeout(() => resolve, 1000) のアロー関数は resolve を返しているだけで、実際には呼び出されていません。そのため、このPromiseは永遠にpendingのままになってしまうと思います。

修正案

// 案1: resolveをコールバックとして直接渡す
async function main() {
  await new Promise((resolve) => {
    setTimeout(resolve, 1000);
  });
}

// 案2: アロー関数内で呼び出す
async function main() {
  await new Promise((resolve) => {
    setTimeout(() => resolve(), 1000);
  });
}

認識に誤りがあればご指摘いただけると幸いです。よろしくお願いします。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions