Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Created April 6, 2023 14:00
Show Gist options
  • Save cowboyd/57386a5db6fdc3a371f49bc5b6ab781a to your computer and use it in GitHub Desktop.
Save cowboyd/57386a5db6fdc3a371f49bc5b6ab781a to your computer and use it in GitHub Desktop.
An "async" function to turn any `Computation` into a `Promise`
import { evaluate, reset, shift, type Computation } from "https://deno.land/x/continuation@0.1.5/mod.ts";
function async<T>(op: () => Computation<T>): Computation<Promise<T>> {
return reset(function*() {
let { resolve, reject } = yield* shift(function*(k) {
return new Promise((resolve, reject) => k({ resolve, reject }));
});
try {
resolve(yield* op());
} catch (error) {
reject(error);
}
});
}
let num = await evaluate(() => async(function*() {
yield* shift(function*(k) { setTimeout(k, 1000 )});
return 5 + 5;
}));
console.dir({ num });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment