7
3

More than 3 years have passed since last update.

node.jsでsleep処理をasync awaitを使って書く

Last updated at Posted at 2020-08-03

sleep処理を書くときはsetTimeoutを使うのが一般的だと思いますが、callbackを書きたくないので今風にasync awaitで書きます。

配列にある会社idの情報を1秒ごとに順番にリクエストする処理を書くと以下のようになります。

index.js
async function sleep(ms) {
  return new Promise(r => setTimeout(r, ms));
}

async function request(id) {
    // 割愛
}

async function exec() {
  const companyIdList = [1, 2, 3, 4, 5];

  for (const id of companyIdList) {
    await sleep(1000);
    await request(id);
  }
}

exec();
7
3
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
7
3