Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Organization

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

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();
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
3
Help us understand the problem. What are the problem?