Skip to content

Instantly share code, notes, and snippets.

@torgeir
Last active June 7, 2017 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torgeir/523a27121a08fbeffc60e348bd2fd49f to your computer and use it in GitHub Desktop.
Save torgeir/523a27121a08fbeffc60e348bd2fd49f to your computer and use it in GitHub Desktop.
Flatten nested promises with asyncawait + then or plain synchronous looking asyncawait.
let wait = (s, data) =>
new Promise(resolve => setTimeout(resolve.bind(null, data),
s * 1000));
let loc = (l) =>
({ location: l });
let region = (r) =>
({ region: r,
locations: [wait(3, loc(`${r} loc 1`)),
wait(4, loc(`${r} loc 2`))]});
let county = () =>
Promise.resolve([wait(1, region('reg 1')),
wait(2, region('reg 2'))]);
let thenable = async () =>
await county()
.then(county => Promise.all(county))
.then(regions => Promise.all(
regions.map(region => region.locations)))
.then(locations => Promise.all(
locations.map(loc => Promise.all(loc))));
console.time('thenable');
thenable()
.then(JSON.stringify)
.then(console.log) // => [[{"location":"reg 1 loc 1"},{"location":"reg 1 loc 2"}],[{"location":"reg 2 loc 1"},{"location":"reg 2 loc 2"}]]
.then(_ => console.timeEnd('thenable')); // => thenable: 4003.666015625ms
let asyncawait = async function () {
let c = await county();
let regions = await Promise.all(c);
let locations = await Promise.all(
regions.map(region => region.locations));
return await Promise.all(
locations.map(async (loc) => await Promise.all(loc)));
};
console.time("asyncawait");
asyncawait()
.then(JSON.stringify)
.then(console.log) // => [[{"location":"reg 1 loc 1"},{"location":"reg 1 loc 2"}],[{"location":"reg 2 loc 1"},{"location":"reg 2 loc 2"}]]
.then(_ => console.timeEnd('asyncawait')); // => asyncawait: 4004.31005859375ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment