Javascript Async Examples

Error propagatioon

It is not necessary to

async function foo() {
  let rand = ~~(Math.random() * 10);
  if (rand % 2) {
    return "Hello";
  } else throw Error("Error at foo!");
}

async function bar() {
  let x = await foo();
  x += " world";
  return x;
}

async function baz() {
  let y = await bar();
  y += "!!!";
  return y;
}

let a = 0;

(async () => {
  for (let i = 0; i < 10; i++) {
    try {
      res = await baz();
      console.log(res);
    } catch (e) {
      a++;
      console.error(e.message) // e.name, e.stack
    }
  }
  console.log(a);
})();
## Hello world!!!
## Error at foo!
## Error at foo!
## Hello world!!!
## Error at foo!
## Error at foo!
## Error at foo!
## Hello world!!!
## Error at foo!
## Error at foo!
## 7