Skip to content

Instantly share code, notes, and snippets.

@Kreijstal
Last active July 8, 2020 21:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kreijstal/2a34158a1cf159b4ddc5ab3460f6efd0 to your computer and use it in GitHub Desktop.
Save Kreijstal/2a34158a1cf159b4ddc5ab3460f6efd0 to your computer and use it in GitHub Desktop.
Promises in Mathematica
(* ::Package:: *)
(*Import like Import["https://gist.githubusercontent.com/Kreijstal/\
2a34158a1cf159b4ddc5ab3460f6efd0/raw/\
6bfc3328d9538844fabbbce9691fb3c63824ed9f/promises.m"]*)
Promise::usage="Promise[Function[{accept,reject},CustomLogic[accept[\"Success!\"],reject[\"Oh no! Error!\"]]]]"
Promise :=
Module[{local, success, failure, listen, counter = 0, Promise},
success[x_] := (local["s"] = x;(*Print[{"I've been executed",x,
local}];*)Through[local["t"][local["s"]]]; local["t"] = {};
local["resolved"] = True);
failure[x_] := (local["f"] = x; Null);
Promise[
f_] := (local = <|"s" -> Null, "f" -> Null, "c" -> {}, "t" -> {},
"resolved" -> False, "counter" -> counter++|>;
local["edit"] :=
Function[{key, value}, (local[key] = value; local)];
local["debug"] := local;
local[
"_whenThened"] := (If[local["resolved"],
Through[local["t"][local["s"]]]; local["t"] = {}, Null]);
f[success, failure]; local); Promise]
Module[{p, accept, reject},
Promisify[
f_] := ((p :=
Promise[Function[{a, r}, (accept := a;
reject := r)]]); {(Function[x, accept[f[x]]]), p})
]
SetAttributes[PromiseThen, HoldAll]
PromiseThen[promise_?AssociationQ,
f_] := (promise["edit"]["t", Join[promise["t"], {#[[1]]}]];
promise["_whenThened"]; promise = promise["debug"]; #[[2]]) &[
Promisify[f]];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment