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?
- Changing outer state within function scope
- async, await, async, await... this is confusing
- 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.
- No more state
- Using Promise library with new ES7 features
- Pulled easy logic into small, reusable function