Last active
August 29, 2015 14:27
-
-
Save avermeulen/56bc4f4f77d9ccde3a4d to your computer and use it in GitHub Desktop.
Taming callbacks with generators
This file contains 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
'use strict' | |
// you need to use iojs for this... or something | |
function async(myGenerator){ | |
return function(){ | |
var theGenerator = myGenerator.apply(this, arguments); | |
function handle(result){ | |
//console.log('handling...') | |
//console.log(result) | |
if (result.done){ | |
//console.log("!") | |
return Promise.resolve(result.value); | |
} | |
//console.log("result value ---> "); | |
//console.log(result.value); | |
return Promise | |
.resolve(result.value) | |
.then(function(res){ | |
//console.log('#') | |
handle(theGenerator.next(res)) | |
}, function(err){ | |
//console.log('!!') | |
handle(theGenerator.throw(err)) | |
}); | |
} | |
try { | |
console.log('start...') | |
return handle(theGenerator.next()); | |
} catch (ex) { | |
return Promise.reject(ex); | |
} | |
}; | |
} | |
var hello = function(){ | |
return new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
resolve("hello") | |
}, 1500); | |
}); | |
} | |
var world = function(){ | |
return new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
resolve("world") | |
}, 1000); | |
}); | |
} | |
var l = async(function* (){ | |
var h = yield hello(); | |
var w = yield world(); | |
console.log("=> " + h + " " + w); | |
}); | |
l(); | |
//console.log(g.next(200)) | |
//console.log(g.next(200)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment