Async/Await サンプル1 - JavaScript

by s_hiroshi

JavaScript

/*
 * async/awaitサンプル1
 * https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function
 * TypeScriptはエラーになります(バージョンの問題かもしれません)。
 */

function resolveAfter1Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 1000);
  });
}

async function add1(x) {
  var a = resolveAfter1Seconds(20);
  var b = resolveAfter1Seconds(30);
  return x + await a + await b;
}

add1(10).then(v => {
  console.log(v); // prints 60 after 1 seconds.
});

async function add2(x) {
  var a = await resolveAfter1Seconds(20);
  var b = await resolveAfter1Seconds(30);
  return x + a + b;
}

add2(20).then(v => {
  console.log(v); // prints 70 after 2 seconds.
});