Skip to content

Commit

Permalink
add the 'do notation' function to Future
Browse files Browse the repository at this point in the history
  • Loading branch information
rpallas92 committed Aug 14, 2018
1 parent 68137e9 commit d74615d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Future.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ export class Future<T> {
return new Future(Lazy.of(()=>Promise.reject(reason)));
}

/**
* Creates a Future from a do-notation block. asyncc/await can use
* inside the block, the result value will be wrapped into a new Future,
* without be worry about add try/catch to the async/await code.
*/
static do<T>(doNotationBlock: ()=>Promise<T>): Future<T> {
return Future.of(doNotationBlock())
}

/**
* The `then` call is not meant to be a part of the `Future` API,
* we need then so that `await` works directly.
Expand Down
35 changes: 35 additions & 0 deletions tests/Future.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,38 @@ describe("Future.on*", () => {
assert.ok(Either.left(5).equals(v));
});
});

describe("Future do notation*", () => {
it("do notation creates a successful future", async () => {
const f1 = Future.ok(1)
const f2 = Future.ok(2)

const f3 = Future.do(async () => {
const v1 = await f1
const v2 = await f2
return v1 + v2
})

const v3 = await f3
assert.deepEqual(3, v3);
});

it("do notation creates a failable future", async () => {
const f1 = Future.ok(1)
const f2 = Future.failed<number>("bad number")

const f3 = Future.do(async () => {
const v1 = await f1
const v2 = await f2
return v1 + v2
})

try {
const v3 = await f3
assert.fail("Error: Future must fail")

} catch (error) {
assert.deepEqual(error, "bad number");
}
});
});

0 comments on commit d74615d

Please sign in to comment.