Last active
May 30, 2017 11:08
-
-
Save royalgarter/14de395e8d811e84d19d9886ae4a26e9 to your computer and use it in GitHub Desktop.
How to write in sync with ES6 (with generator & yield explanation). Thanks to Mr.Lucioato, author of waitfor-ES6 (https://github.com/luciotato/waitfor-ES6)
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
"use strict"; | |
const sync = function(fnGenerator) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
/**/ console.log('sync args', args.length, args) | |
const callAsync = (funcAndArgs, callback) => { | |
const argsOnly = Array.prototype.slice.call(funcAndArgs, 1); | |
argsOnly.push(callback); | |
/**/ console.log('callAsync', argsOnly) | |
funcAndArgs[0].apply(null, argsOnly); | |
} | |
const iterator = fnGenerator.apply(null, args); | |
iterator.myCallback = (err, data) => { | |
/**/ console.log('\nmyCallback', err, data) | |
if (err) return iterator.throw(err); | |
/**/ console.log('calling next') | |
const nextPart = iterator.next(data); | |
/**/ console.log('nextPart', nextPart) | |
if (!nextPart.done) | |
return callAsync(nextPart.value, iterator.myCallback); | |
}; | |
iterator.myCallback(); | |
return iterator; | |
} | |
const demoCallback = (v1, v2, callback) => { | |
console.log('demoCallback'); | |
setTimeout( () => { | |
console.log('demoCallback v1', v1, 'v2', v2); | |
return callback(null, 'demoCallback done'); | |
}, 1e3) | |
} | |
function* demoGenerator() { | |
/**/ console.log('demoGenerator'); | |
var args = Array.prototype.slice.call(arguments, 0); | |
/**/ console.log('demoGenerator args', args.length, args) | |
const data1 = yield [demoCallback, 1, 2]; | |
console.log('data1', data1); | |
const data2 = yield [demoCallback, 3, 4]; | |
console.log('data2', data2); | |
} | |
sync(demoGenerator, 'a', 'b', 'c') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment