Skip to content

Instantly share code, notes, and snippets.

@ChrisChares
Last active September 30, 2022 13:26
Show Gist options
  • Star 75 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ChrisChares/1ed079b9a6c9877ba4b43424139b166d to your computer and use it in GitHub Desktop.
Save ChrisChares/1ed079b9a6c9877ba4b43424139b166d to your computer and use it in GitHub Desktop.
async/await with ES6 Generators & Promises

async/await with ES6 Generators & Promises

This vanilla ES6 function async allows code to yield (i.e. await) the asynchronous result of any Promise within. The usage is almost identical to ES7's async/await keywords.

async/await control flow is promising because it allows the programmer to reason linearly about complex asynchronous code. It also has the benefit of unifying traditionally disparate synchronous and asynchronous error handling code into one try/catch block.

This is expository code for the purpose of learning ES6. It is not 100% robust. If you want to use this style of code in the real world you might want to explore a well-tested library like co, task.js or use async/await with Babel. Also take a look at the official async/await draft section on desugaring.

Compatibility

  • node.js - 4.3.2+ (maybe earlier with --harmony flag)
  • browser - (if you have Promises && Generators)
  • babel 👍 { "presets": ["es2015"] }

Background Reading

Furthur

  • Return Promise from async to support chaining
  • Support other asynchronous actions like thunks or nested generators
/**
 *	@param {Generator} gen Generator which yields Promises
 *	@param {Any} context last resolved Promise value, currently only used recursively
 */
function async(gen, context = undefined) {
	const generator = typeof gen === 'function' ? gen() : gen; // Create generator if necessary
	const { value: promise } = generator.next(context); // Pass last result, get next Promise
	if ( typeof promise !== 'undefined' ) {
		promise.then(resolved => async(generator, resolved))
		.catch(error => generator.throw(error)); // Defer to generator error handling
	}
}

/* Usage */
async(function* () { // Generators can't be declared with arrow syntax
	try {
		// Execution is paused until the yielded promise resolves
		console.log(yield Promise.resolve('A Mortynight Run'))
		// Promises already provide support for concurrent async actions.
		// Execution will not continue until both a & b are fulfilled
		const [a,b] = yield Promise.all([
			Promise.resolve('Get Schwifty'),
			Promise.resolve('The Ricks Must Be Crazy')
		]);
		console.log(a + ' ' + b);
		// Rejected promises will be handled by try/catch as if code was synchronous
		const seasonTwoFinale = yield Promise.reject(new Error('Tammy'));
		// Never executed
		const seasonThree = 'Coming Soon';
	} catch (error) {  console.error(error.message);  } // Tammy
})
@ChrisChares
Copy link
Author

@rgeraldporter fixed, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment