0
1

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 3 years have passed since last update.

JavaScript/node.jsでsleep

Last updated at Posted at 2020-08-06

ちょっとしたことだけど、JavaScriptにはsleepがないので。

async () => {
    // 前の処理
    await new Promise(resolve => setTimeout(resolve, 1000));
    // 1秒待った後の処理...
}

JavaScriptに馴染みのないサーバーサイドの方向けに説明

setTimeout

setTimeout(コールバック, ミリ秒)でミリ秒後にコールバックを実行します。JSのタイマー処理の基本。

Promise

new Promise()でPromiseオブジェクトを取得します。Promiseオブジェクトは非同期処理が完了したら結果がもらえるやつです。

const 結果のPromise = new Promise(resolve => {
    // 任意の処理
    resolve(結果);
});

await

await Promiseオブジェクトで結果を取り出せます。async関数の中で使う必要があります。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?