Chain async functions
This answer by Tamas Hegedus with parentheses around the await
expressions is definitely the way to go with vanilla JavaScript.
Alternatively, if you're looking for commonly chained JS methods and don't mind a third-party module you can use async-af on npm. With that you can chain asynchronous methods like so:
const promises = [1, 2, 3].map(n => Promise.resolve(n));
AsyncAF(promises).map(n => n * 2).filter(n => n !== 4).forEach(n => console.log(n));
// logs 2 then 6
<script src="https://unpkg.com/[email protected]/index.js"></script>
you can try this package.
- prochain npm
- prochain github
// Instead of thens
fetch(url)
.then(res => res.json())
.then(json => json.foo.bar)
.then(value => console.log(value))
// Instead of awaits
const res = await fetch(url)
const json = await res.json()
const value = json.foo.bar
console.log(value)
// With prochain
const value = await wrap(fetch(url)).json().foo.bar
console.log(value)
You can await in an expression, no need to assign it to a new variable. (Although assigning it to a variable is probably more readable.)
const foo = await (await myAsyncFunction()).somethingElseAsync()
Or if you want to call a sync method on the result:
const foo = (await myAsyncFunction()).somethingElseSync()
I'm surprised that it's not already mentioned, but probably the most readable way to achieve this without extra variables is to use a .then
chain, and await
that at the end:
await myAsyncFunction()
.then(res => res.somethingElse())
Remember, await
works together with promises, but doesn't replace them!