Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Convert js-style callback to Future, with macro
Convert js-style callback to Future, with macro
abstract Wrapper(Model) from Model
public inline function find(query:Dynamic):Surprise<Model, Error>
// insert the above js-style to future code here...
public inline function update(query:Dynamic, data:Dynamic):Surprise<UpdateResult, Error>
// modify and insert the above js-style to future code here...
package util;
import haxe.macro.Context;
import haxe.macro.Expr;
using tink.MacroApi;
class Macro
public static macro function futurize(expr:Expr):Expr
var newExpr = expr.transform( replaceCallbacks );
return macro @:pos(Context.currentPos()) {
var t = new tink.CoreApi.FutureTrigger();
static function replaceCallbacks(expr:Expr):Expr
return switch expr {
case macro $i{"$cb"}: macro @:pos(expr.pos) function(e, d) t.trigger(e != null ? Failure(e) : Success(d));
case macro $i{"$cb0"}: macro @:pos(expr.pos) function(e) t.trigger(e != null ? Failure(e) : Success(tink.CoreApi.Noise.Noise));
case other: other;
// Convert js-style callback to a future, to better integrate with ufront
var trigger = new FutureTrigger();
myModelManager.find({}, function(err, data) trigger.trigger(err != null ? Failure(err) : Success(data)));
var future = trigger.asFuture();
var findFuture = futurize(myModelManager.find({}, $cb));
// countFuture is Surprise<Array<MyModel>, Error>
var updateFuture = futurize(myModelManager.update({}, {data:data}, $cb));
// countFuture is Surprise<UpdateResult, Error>
var countFuture = futurize(myModelManager.where('field', value).count($cb));
// countFuture is Surprise<Int, Error>
var removeFuture = futurize(myModelManager.remove({}, $cb0));
// removeFuture is Surprise<Noise, Error> (note the zero in $cb0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment