Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function spawn(generatorFunc) {
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (err) {
return Promise.reject(err);
}
if (result.done) {
return result.value;
} else {
return Promise.resolve(result.value).then(onFulfilled, onRejected);
}
}
var generator = generatorFunc();
var onFulfilled = continuer.bind(continuer, "next");
var onRejected = continuer.bind(continuer, "throw");
return onFulfilled();
}
@taralx
Copy link

taralx commented Apr 29, 2017

@jakearchibald I have this. Although it doesn't handle returning a value, it has some advantages. :-)

function spawn(gen) {
	return function(...args) {
		let iter = gen(...args);
		function step({value, done}) {
			if (!done) value.then(v => iter.next(v), e => iter.throw(e)).then(step);
		}
		step(iter.next());
	}
}

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