aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2021-08-29 17:18:37 +0100
committerLouis Pilfold <louis@lpil.uk>2021-08-29 17:18:37 +0100
commitc2d25106df806fd9de96f1ab3186102ba27dceab (patch)
tree833f17fd6e3821f6ee2d536ecdef96cc3418d944 /src
parent08bf033063a8d3ce789939bac36ed39fc6bc2eca (diff)
downloadjavascript-c2d25106df806fd9de96f1ab3186102ba27dceab.tar.gz
javascript-c2d25106df806fd9de96f1ab3186102ba27dceab.zip
Promises
Diffstat (limited to 'src')
-rw-r--r--src/ffi.js30
-rw-r--r--src/gleam/javascript/promise.gleam11
2 files changed, 41 insertions, 0 deletions
diff --git a/src/ffi.js b/src/ffi.js
index 07e7b0f..450f5e3 100644
--- a/src/ffi.js
+++ b/src/ffi.js
@@ -64,3 +64,33 @@ export function type_of(value) {
export function get_symbol(name) {
return Symbol.for(name);
}
+
+// A wrapper around a promise to prevent `Promise<Promise<T>>` collapsing into
+// `Promise<T>`.
+class PromiseLayer {
+ constructor(promise) {
+ this.promise = promise;
+ }
+
+ static wrap(value) {
+ return value instanceof Promise ? new PromiseLayer(value) : value;
+ }
+
+ static unwrap(value) {
+ return value instanceof PromiseLayer ? value.promise : value;
+ }
+}
+
+export function resolve(value) {
+ return Promise.resolve(PromiseLayer.wrap(value));
+}
+
+export function then(promise, fn) {
+ return promise.then((value) => fn(PromiseLayer.unwrap(value)));
+}
+
+export function map_promise(promise, fn) {
+ return promise.then((value) =>
+ PromiseLayer.wrap(fn(PromiseLayer.unwrap(value)))
+ );
+}
diff --git a/src/gleam/javascript/promise.gleam b/src/gleam/javascript/promise.gleam
new file mode 100644
index 0000000..4f8d54c
--- /dev/null
+++ b/src/gleam/javascript/promise.gleam
@@ -0,0 +1,11 @@
+// TODO: docs
+pub external type Promise(value)
+
+pub external fn resolve(value) -> Promise(value) =
+ "../../ffi.js" "resolve"
+
+pub external fn then(Promise(a), fn(a) -> Promise(b)) -> Promise(b) =
+ "../../ffi.js" "then"
+
+pub external fn map(Promise(a), fn(a) -> b) -> Promise(b) =
+ "../../ffi.js" "map_promise"