Created
April 6, 2023 14:00
-
-
Save cowboyd/57386a5db6fdc3a371f49bc5b6ab781a to your computer and use it in GitHub Desktop.
An "async" function to turn any `Computation` into a `Promise`
This file contains 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
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