Skip to content

Instantly share code, notes, and snippets.

@dijs
Created October 27, 2015 19:58
Show Gist options
  • Save dijs/ede589ee3d65c191fb24 to your computer and use it in GitHub Desktop.
Save dijs/ede589ee3d65c191fb24 to your computer and use it in GitHub Desktop.
Async/await do for each ideas

ES7's async/await is awesome!

But, in order to use it well, you need to think in promises.

First thought:

async function something() => {
  let state = []
  await [1, 2, 3].forEach(async(n) => {
    let k = await Promise.resolve(n + 1)
    state.push(k)
  })
  return state
}

So... this works, but it is impossible to digest for everyone but the developer. And they probably won't understand it either.

What is wrong here?

  1. Changing outer state within function scope
  2. async, await, async, await... this is confusing
  3. Doing a transform with temporary state and foreach

Let's try again

function fetch(n) {
  return Promise.resolve(n + 1)
}
async function something() => {
  return await Promise.all([1, 2, 3].map(fetch))
}

Much better.

  1. No more state
  2. Using Promise library with new ES7 features
  3. Pulled easy logic into small, reusable function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment