Skip to content

Instantly share code, notes, and snippets.

@fujidig
Created September 21, 2011 09:39
Show Gist options
  • Save fujidig/1231670 to your computer and use it in GitHub Desktop.
Save fujidig/1231670 to your computer and use it in GitHub Desktop.
function deferredTimeout(delay) {
var deferred = new Deferred();
window.setTimeout(function() {
deferred.callback({});
},
delay);
return deferred;
}
function yieldToAwait(src) {
return function () {
var deferred = new Deferred();
var generator = src.apply(this, arguments);
function loop(val) {
try {
var ret = generator.send(val);
ret.then(loop);
} catch (e if e instanceof StopIteration) {
deferred.callback();
}
}
loop(undefined);
return deferred;
}
}
function a() {
for (var i = 0; i < 4; ++i) {
console.log("a"+i);
yield deferredTimeout(100);
}
}
var d = yieldToAwait(a)();
d.then(function() { console.log("done") });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment