LoginSignup
6
4

More than 5 years have passed since last update.

JavaScriptで非同期関数を順々に実行

Last updated at Posted at 2017-09-23

個数が分かってて順々に実行するなら、

async function fn(): Promise<void> {
  await a();
  await b();
  await c();
  return;
}

とにかく並行に実行なら、

await Promise.all([a, b, c].map(fn => fn());

個数が分からなくて順々に実行するなら? » for..ofとかで回せば良さげ。

async function fn(): Promise<void> {
  for (const fn of [a, b, c]) {
    await fn();
  }
}

function genNumber() {
  return Math.floor(Math.random() * 10);
}

function sleep(): Promise<{}> {
  return new Promise(resolve => {
    setTimeout(resolve, 1000);
  });
}

function log(text: string): () => Promise<void> {
  return async () => {
    await sleep();
    console.log(text);
  }
}

const fns = Array<string>(genNumber())
  .fill('')
  .map(() => log(String(genNumber())));

(async () => {
  for (const fn of fns) {
    await fn();
  }
})();

# 4
# 1
# 2
# 9
# 3
# 2
# 1
# 3

» ちょっと悩んだ。

6
4
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
6
4