Last active
February 15, 2017 20:15
-
-
Save zdychacek/8420529 to your computer and use it in GitHub Desktop.
Async calls with self implemented async function
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'; | |
function async (generator, callback) { | |
if (generator.constructor.name !== 'GeneratorFunction') { | |
throw new Error('Function async accept only generator function.'); | |
} | |
function handleResult (result) { | |
let resultValue = result.value; | |
if (result.done) { | |
return callback(resultValue); | |
} | |
// handle promise, resp. any thenable | |
if (typeof resultValue.then === 'function') { | |
resultValue.then(function (data) { | |
handleResult(genInstance.next(data)); | |
}, function (err) { | |
genInstance.throw(err); | |
}); | |
} | |
// handle generator | |
else if (resultValue.constructor.name === 'GeneratorFunction') { | |
// TODO: handle errors from inner generators | |
async(resultValue, function (data) { | |
handleResult(genInstance.next(data)); | |
}); | |
} | |
// handle thunk | |
else if (typeof resultValue === 'function') { | |
resultValue(function (err, result) { | |
if (err) { | |
return genInstance.throw(err); | |
} | |
let args = resultValue; | |
// if there are more than two parameters, then slice first err param | |
if (arguments.length > 2) { | |
args = [].slice.call(arguments, 1); | |
} | |
handleResult(genInstance.next(args)); | |
}); | |
} | |
} | |
let genInstance = generator(); | |
handleResult(genInstance.next()); | |
} | |
function sleep (time) { | |
return function (callback) { | |
setTimeout(callback, time); | |
} | |
} | |
function sleepPromise (time) { | |
return new Promise(function (resolve, reject) { | |
setTimeout(resolve, time); | |
}); | |
} | |
function* innerTask () { | |
yield sleepPromise(1000); | |
console.log(3); | |
yield sleepPromise(1000); | |
console.log(4); | |
} | |
async(function* () { | |
console.log(1); | |
yield sleep(1000); | |
console.log(2); | |
yield innerTask; | |
try { | |
throw new Error('My error'); | |
} | |
catch (ex) { | |
console.log(`Error catched: "${ex.message}".`); | |
} | |
yield sleep(1000); | |
console.log(5); | |
return 'Terezka'; | |
}, function (retValue) { | |
console.log(`Finished with value: "${retValue}".`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment