Skip to content

Instantly share code, notes, and snippets.

@YNSTakeru
Last active March 17, 2024 19:48
Show Gist options
  • Save YNSTakeru/7d9cc2c16f37ecd7ee7099b83ea850d7 to your computer and use it in GitHub Desktop.
Save YNSTakeru/7d9cc2c16f37ecd7ee7099b83ea850d7 to your computer and use it in GitHub Desktop.

問題3 ヒント

クリックして開く

async,awaitよりthen使うといいかも?

問3 解答

クリックして開く
function delay(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

function* asyncIterator(data) {
  for (const ms of data) {
    const index = data.indexOf(ms);
    yield delay(ms, index);
  }
}

const data = [];
const iterator = asyncIterator(data);

(async () => {
  for (let i = 0; i < 5; i++) {
    const X = Math.floor(Math.random() * 5000);
    data.push(X);
  }
  console.log(data);

  for (const promise of iterator) {
    promise.then((result) => console.log(result));
  }
})();

`async`,`await`を使うと、処理が完了するまで待機してしまいます。`asyncIterator`には`yield``Promise`だけ
を渡し、呼び出し側で`then`を実行することで非同期処理を実現します
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment