Skip to content

Instantly share code, notes, and snippets.

@RobertLowe
Created March 14, 2018 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertLowe/007e3e0fdb0a75b6fd06fcecb9019c7b to your computer and use it in GitHub Desktop.
Save RobertLowe/007e3e0fdb0a75b6fd06fcecb9019c7b to your computer and use it in GitHub Desktop.
Stop using async with Meteor. Futures are the future (still).
// Go forth and code with the simplicity of sync
//
// PSA: this isn't production ready, and just a PoC, but enjoy using it!
// server only, as we need fibers (co-routines)!
import Future from 'fibers/future';
let resolving = (object, operation, ...args)=>{
let future = new Future();
let handleError = Meteor.bindEnvironment((error)=>{
// bubble with original error
future.throw(error);
});
let handleSuccess = Meteor.bindEnvironment((...results)=>{
future.return( (results.length == 1) ? results[0] : results );
});
let handle = Meteor.bindEnvironment((error, ...results)=>{
if(error){
handleError(error);
} else {
handleSuccess(...results)
}
});
// a promise shouldn't care about an overloaded function signature
let maybe = object[operation](...args, handle);
if(maybe instanceof Promise){
maybe.then(handleSuccess).catch(handleError);
}
return future.wait();
}
// async:
let thing = new ThingThatUsesAsync();
let something = resolving(thing, 'getSomething');
let somethingElse = resolving(thing, 'getSomethingElse');
// promises:
let thing = new ThingThatUsesPromises();
let result = resolving(thing, 'listThings', 'someParam', 'anotherParam' );
// error handling?
try {
let thing = new ThingThatUsesAsync();
let result = resolving(thing, 'getThing');
} catch (error) {
console.log("Something went wrong", error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment