2020年9月7日月曜日

Node.jsで複数のリソースからsleepしながらfetch

Node.js の非同期処理が苦手過ぎるので、Node.js で複数のリソースから sleep しながら fetch するサンプルを載せておきます。 API を使う時によく使う割にハマりやすい。


const fetch = require('node-fetch')

function sleep(time) {
  const d1 = new Date();
  while (true) {
    const d2 = new Date();
    if (d2 - d1 > time) {
      return;
    }
  }
}

// ここで API の仕様に沿った実装をする
function fetchFromABC(id) {
  return new Promise((resolve, reject) => {
    fetch('https://hoge.com/' + id)
    .then(response => response.json())
    .then(data => {
      // process.stdout.write(id);  // 進捗表示
      sleep(1000);  // sleep しながら同期的に取得
      resolve(data);  // 取得データを返却
    });
  }));
}

// sleep しながら取得する
async function fetchFromABCMultiple(ids) {
  var info = {};
  for (var i=0; j<ids.length; i++) {
    await fetchFromABC(ids[i]).then(res) => {
      info[i] = res;
    });
  }
}

var ids = [1, 2, 3, 4, 5];
fetchFromABCMulpile(ids).then(info => {
  console.log(info);
});

書き方に慣れないとこのへん本当にハマりやすいよなあ。

0 件のコメント: