Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@navix
Forked from StevenACoffman/async javascript.md
Created September 21, 2017 18:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/ec0a684481cb30d38817d8f72b084ef1 to your computer and use it in GitHub Desktop.
Save navix/ec0a684481cb30d38817d8f72b084ef1 to your computer and use it in GitHub Desktop.
Async Await in 7 seconds

Async / Await in 7 seconds

by Wassim Chegham (@manekinekko)

From this awesome animation, originally from this tweet

Callbacks (continuation passing style)

getData( a => {
	getMoreData(a, b => {
		getMoreData(b, c => {
			getMoreData(c, d => {
				getMoreData(d,e => {
					console.log(e);
				});
			});
		});
	});
});

Promises (with anonymous functions argument)

getData()
.then(a => getMoreData(a))
.then(b => getMoreData(b))
.then(c => getMoreData(c))
.then(d => getMoreData(d))
.then(e => getMoreData(e));

Promises (with named function argument)

getData()
.then(getMoreData)
.then(getMoreData)
.then(getMoreData)
.then(getMoreData)
.then(getMoreData);

Async Await

(async () => {
	const a = await getData();
	const b = await getMoreData(a);
	const c = await getMoreData(b);
	const d = await getMoreData(c);
	const e = await getMoreData(d);
	console.log(e);
})();

Async Await with Exception Handling

(async () => {
	try {
		const a = await getData();
		const b = await getMoreData(a);
		const c = await getMoreData(b);
		const d = await getMoreData(c);
		const e = await getMoreData(d);
		console.log(e);
	}
	catch(me) {
		// if you can
	}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment