profileRyan KesPGP keyI build stuffEmailGithubTwitterLast.fmMastodonMatrix

JavaScript For Await Of

Syntax

async function f() {
  for await (const x of createAsyncIterable(["a", "b"])) {
    console.log(x)
  }
}
// Output:
// a
// b

Rejections

Like await in async functions, th eloop throws an exception if next() returns a rejection:

function createRejectingIterable() {
  return {
    [Symbol.asyncIterator]() {
      return this
    },
    next() {
      return Promise.reject(new Error("Problem!"))
    },
  }
}
;(async function () {
  // (A)
  try {
    for await (const x of createRejectingIterable()) {
      console.log(x)
    }
  } catch (e) {
    console.error(e)
    // Error: Problem!
  }
})() // (B)

Related