346
202

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

awaitできるsetTimeoutを1行で書く方法

Last updated at Posted at 2019-10-28

awaitすることができるsetTimeoutを1行で書くイディオムです。

await new Promise(resolve => setTimeout(resolve, 3000)) // 3秒待つ

// ... 3秒後の処理 ...

おまけ: よくある長めの実装からの変形手順

// よくある長めの実装
const sleep = () => new Promise(resolve => {
  setTimeout(() => {
    resolve()
  }, 3000)
})
await sleep()

// ステップ1: () => { resolve() } は resolve に短縮する
const sleep = () => new Promise(resolve => {
  setTimeout(resolve, 3000)
})
await sleep()

// ステップ2: resolve => {} は resolve => に短縮する
const sleep = () => new Promise(resolve => setTimeout(resolve, 3000))
const promise = sleep()
await promise

// ステップ3: sleep()は関数でなくていいので値にする
const promise = new Promise(resolve => setTimeout(resolve, 3000))
await promise

// ステップ4: 完成
await new Promise(resolve => setTimeout(resolve, 3000))
346
202
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
346
202

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?