Help us understand the problem. What is going on with this article?

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

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))
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした