Created
March 14, 2018 03:29
-
-
Save RobertLowe/007e3e0fdb0a75b6fd06fcecb9019c7b to your computer and use it in GitHub Desktop.
Stop using async with Meteor. Futures are the future (still).
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
// 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