Skip to content

Instantly share code, notes, and snippets.

@zebulonj
Created February 3, 2018 08:20
Show Gist options
  • Save zebulonj/c717448352ffed7a2b4eb1845ad8e8a8 to your computer and use it in GitHub Desktop.
Save zebulonj/c717448352ffed7a2b4eb1845ad8e8a8 to your computer and use it in GitHub Desktop.
Async/Await with Generators... the ultimate in decoupling!
import test from 'tape';
const query = async () => ({ value: 'Z' });
const call = ( fn, ...params ) => ({ fn, params });
const create = function *( formId ) {
const form = yield call( query, 'SELECT', formId );
return form;
};
const connect = ( generator ) => async ( ...input ) => {
const iter = generator( ...input );
let step = iter.next();
while ( !step.done ) {
let { fn, params } = step.value;
let result = await fn( ...params );
step = iter.next( result );
}
return step.value;
}
test( "Async/await with generators...", async assert => {
const iter = create( 'X' );
const step1 = iter.next();
assert.deepEquals( step1.value, { fn: query, params: ['SELECT', 'X'] }, 'Should emit a call, with the correct function and parameters.' );
const step2 = iter.next( 'Y' );
assert.equals( step2.value, 'Y', 'Should yield the loaded form.' );
const result = await connect( create )( 'X' );
assert.deepEquals( result, { value: 'Z' }, 'Should return the correct result when connected.' );
assert.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment