yasutomogのブログ

Software Engineerの雑記

JavaScriptの色々な非同期処理の書き方(callback、promise、async/await)

概要

  • callback、promise、async/awaitの3パターンで非同期処理を書いてみる

内容

callback

function add1000(n) {
  setTimeout(() => {
    console.log(n + 1000);
  }, 2000);
}

function add100(n) {
  setTimeout(() => {
    console.log(n + 100);
    add1000(n + 100)
  }, 2000);
}

function add10(n) {
  setTimeout(() => {
    console.log(n + 10);
    add100(n + 10);
  }, 2000);
}

function proc(n) {
  console.log(n);
  add10(n);
}

proc(1);

promise

function add1000(n) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(n + 1000);
    }, 2000);
  });
}

function add100(n) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(n + 100);
    }, 2000);
  });
}

function add10(n) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(n + 10);
    }, 2000);
  });
}

function proc(n) {
  console.log(n);
  add10(n).then((r) => {
    console.log(r);
    return add100(r);
  }).then((r) => {
    console.log(r);
    return add1000(r);
  }).then((r) => {
    console.log(r);
  });
}

proc(1);

async/await

function add1000(n) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(n + 1000);
    }, 2000);
  });
}

function add100(n) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(n + 100);
    }, 2000);
  });
}

function add10(n) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(n + 10);
    }, 2000);
  });
}

async function proc(n) {
  console.log(n);
  n = await add10(n);
  console.log(n);
  n = await add100(n);
  console.log(n);
  n = await add1000(n);
  console.log(n);
}

proc(1);

github

github.com

  • それぞれjsファイルを用意しているので、index.htmlで読み込むjsを変えて試してみる
  • 手っ取り早く試すには「Web Server for Chrome」を使ってブラウザで開いて、開発ツールのコンソール立ち上げればOK