Created
November 29, 2012 05:49
-
-
Save lukehoban/4167048 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Spawn function inspired by Q.async at http://wiki.ecmascript.org/doku.php?id=strawman:async_functions#reference_implementation | |
// Takes an ES6 generator function and produces a WinJS.Promise | |
function spawn(generatorFunc) { | |
return new WinJS.Promise(function (c, e) { | |
var generator = generatorFunc(); | |
var callback = continuer.bind(void 0, 'send'); | |
var errback = continuer.bind(void 0, 'throw'); | |
function continuer(verb, valueOrErr) { | |
var promisedValue; | |
try { | |
promisedValue = generator[verb](valueOrErr); | |
} catch (err) { | |
if (isStopIteration(err)) { return c(err.value); } | |
return e(err); | |
} | |
return promisedValue.then(callback, errback); | |
} | |
return callback(undefined); | |
}); | |
} | |
// Helpers for the ES6 Generator abstraction - these are provided by the environment in ES6 | |
function StopIteration(value) { this.value = value; } | |
function isStopIteration(e) { return e instanceof StopIteration; } | |
// Hand rolled generator implementation - aims to do the same as: | |
// function* myGen() { | |
// console.log('starting'); | |
// yield WinJS.Promise.timeout(1000); | |
// console.log('resuming from 1 sec sleep'); | |
// yield WinJS.Promise.timeout(2000); | |
// console.log('resuming from 2 sec sleep'); | |
// return "I'm done!!!"; | |
// } | |
function myGen() { | |
var state = 0; | |
return { | |
send: function (v) { | |
switch (state) { | |
case 0: | |
console.log('starting'); | |
state = 1; | |
return WinJS.Promise.timeout(1000); | |
case 1: | |
console.log('resuming from 1 sec sleep'); | |
state = 2; | |
return WinJS.Promise.timeout(2000); | |
case 2: | |
console.log('resuming from 2 sec sleep'); | |
state = -1; | |
throw new StopIteration("I'm done!!!"); | |
} | |
}, | |
} | |
} | |
// Spawn the generator to get back a promise for it's completion | |
var p = spawn(myGen) | |
// 3 seconds later, this should get invoked with "I'm done!!!" | |
p.then(function(x) { | |
console.log(x); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment