Skip to content

Instantly share code, notes, and snippets.

@ojhaujjwal
Last active August 4, 2025 05:45
Show Gist options
  • Save ojhaujjwal/0d02e0038a7174ea766e732d33fcae39 to your computer and use it in GitHub Desktop.
Save ojhaujjwal/0d02e0038a7174ea766e732d33fcae39 to your computer and use it in GitHub Desktop.
intro-to-effect
try {
const doc = await s3.getObject();
} catch (err) {
// error is any or unknown
if (err instanceof ObjectNotFoundError) {
// TODO: handle error
}
}
// Promise<number>
const task = new Promise<number>((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.5 ? resolve(2) : reject("Uh oh!")
}, 300)
});
// vs
// Effect.Effect<number, string, never>
const task = Effect.gen(function* () {
yield* Effect.sleep("300 millis")
return Math.random() > 0.5 ? 2 : yield* Effect.fail("Uh oh!")
});
// Promise<number>
const task = async () => {
await promisify(setTimeout)(300);
return Math.random() > 0.5 ? resolve(2) : reject("Uh oh!");
};
// vs
// Effect.Effect<number, string, never>
const task = Effect.gen(function* () {
yield* Effect.sleep("300 millis")
return Math.random() > 0.5 ? 2 : yield* Effect.fail("Uh oh!")
})
// Promise<number>
const length = Promise.resolve("Hello")
.then((s) => s.length);
//vs
// Effect.Effect<number, never, never>
const length = Effect.succeed("Hello").pipe(
Effect.map((s) => s.length)
)
async function main() {
// number
const length = (await Promise.resolve("Hello")).length;
}
Effect.gen(function* () {
// number
const length = (yield* Effect.succeed("Hello")).length;
});
// Effect.Effect<number, string, never>
const randomNumber = () => Effect.gen(function* () {
return Math.random() > 0.5 ? 2 : yield* Effect.fail("Uh oh!")
});
const program = Effect.gen(function* () {
const randomNumber = yield* randomNumber();
console.log(`Randon number: ${randomNumber}`);
});
Effect.runFork(program)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment