Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise <-> Future conversion #119

Merged
merged 5 commits into from
May 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/source/en/data/conversions/future-to-promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@annotate: folktale.data.conversions.futureToPromise
category: Converting from Futures
---

Converts a Future into a Promise.

Note that this conversion may not be as accurate due to the differences in Promise and Future semantics. In particular, Promises recursively flatten any object with a `.then` method, and do not have a separate representation for cancellations.

Cancelled futures are converted to rejected promises with a special `Cancelled()` object.


## Example::

const futureToPromise = require('folktale/data/conversions/future-to-promise');
const Future = require('folktale/data/future');

$ASSERT(
(await futureToPromise(Future.of(1))) == 1
);

try {
await futureToPromise(Future.rejected(1));
throw 'never happens';
} catch (e) {
$ASSERT(e == 1)
}
21 changes: 21 additions & 0 deletions docs/source/en/data/conversions/promise-to-future.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
@annotate: folktale.data.conversions.promiseToFuture
category: Converting from Promises
---

Converts a Promise to a folktale Future.

Note that this conversion may not be as accurate due to the differences in Promise and Future semantics. In particular, Promises recursively flatten any object with a `.then` method, and do not have a separate representation for cancellations.

If a Promise contains a rejection with Folktale's special `Cancelled()` value, then the resulting Future will be a cancelled Future rather than a rejected one.


## Example::

const promiseToFuture = require('folktale/data/conversions/promise-to-future');

promiseToFuture(Promise.resolve(1));
// => Future.resolve(1)

promiseToFuture(Promise.reject(1));
// => Future.reject(1)

21 changes: 21 additions & 0 deletions docs/source/en/data/future/fromPromise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
@annotate: folktale.data.future.fromPromise
category: Converting from other types
---

Converts a Promise to a folktale Future.

Note that this conversion may not be as accurate due to the differences in Promise and Future semantics. In particular, Promises recursively flatten any object with a `.then` method, and do not have a separate representation for cancellations.

If a Promise contains a rejection with Folktale's special `Cancelled()` value, then the resulting Future will be a cancelled Future rather than a rejected one.


## Example::

const { fromPromise } = require('folktale/data/future');

fromPromise(Promise.resolve(1));
// => Future.resolve(1)

fromPromise(Promise.reject(1));
// => Future.reject(1)

25 changes: 25 additions & 0 deletions docs/source/en/data/future/toPromise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@annotate: folktale.data.future._Future.prototype.toPromise
category: Converting to other types
---

Converts a Future into a Promise.

Note that this conversion may not be as accurate due to the differences in Promise and Future semantics. In particular, Promises recursively flatten any object with a `.then` method, and do not have a separate representation for cancellations.

Cancelled futures are converted to rejected promises with a special `Cancelled()` object.


## Example::

const Future = require('folktale/data/future');

$ASSERT(
(await Future.of(1).toPromise()) == 1
);

try {
await Future.rejected(1).toPromise();
throw 'never happens';
} catch (e) {
$ASSERT(e == 1)
}
29 changes: 29 additions & 0 deletions src/data/conversions/future-to-promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

const { Cancelled } = require('folktale/data/future/_execution-state');


/*~
* stability: experimental
* type: |
* forall e, v:
* (Future e v) => Promise v e
*/
const futureToPromise = (aFuture) => {
return new Promise((resolve, reject) => {
aFuture.listen({
onResolved: (value) => resolve(value),
onRejected: (error) => reject(error),
onCancelled: () => reject(Cancelled())
});
});
}

module.exports = futureToPromise;
4 changes: 3 additions & 1 deletion src/data/conversions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ module.exports = {
nullableToValidation: require('./nullable-to-validation'),
nullableToResult: require('./nullable-to-result'),
nullableToMaybe: require('./nullable-to-maybe'),
nodebackToTask: require('./nodeback-to-task')
nodebackToTask: require('./nodeback-to-task'),
futureToPromise: require('./future-to-promise'),
promiseToFuture: require('./promise-to-future')
};

35 changes: 35 additions & 0 deletions src/data/conversions/promise-to-future.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

const { Cancelled } = require('folktale/data/future/_execution-state');
const Deferred = require('folktale/data/future/_deferred');

/*~
* stability: experimental
* type: |
* forall e, v:
* (Promise v e) => Future e v
*/
const promiseToFuture = (aPromise) => {
const deferred = new Deferred();
aPromise.then(
(value) => deferred.resolve(value),
(error) => {
if (Cancelled.hasInstance(error)) {
deferred.cancel();
} else {
deferred.reject(error);
}
}
)
return deferred.future();
};


module.exports = promiseToFuture;
21 changes: 21 additions & 0 deletions src/data/future/_future.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,17 @@ class Future {
inspect() {
return this.toString();
}


/*~
* stability: experimental
* type: |
* forall e, v:
* (Future e v).() => Promise v e
*/
toPromise() {
return require('folktale/data/conversions/future-to-promise')(this);
}
}


Expand All @@ -247,6 +258,16 @@ Object.assign(Future, {
let result = new Future(); // eslint-disable-line prefer-const
result._state = Rejected(reason);
return result;
},


/*~
* stability: experimental
* type: |
* forall e, v: (Promise v e) => Future e v
*/
fromPromise(aPromise) {
return require('folktale/data/conversions/promise-to-future')(aPromise);
}
});

Expand Down
1 change: 1 addition & 0 deletions src/data/future/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const Future = require('./_future');
module.exports = {
of: Future.of,
rejected: Future.rejected,
fromPromise: Future.fromPromise,
_Deferred: require('./_deferred'),
_ExecutionState: require('./_execution-state'),
_Future: Future
Expand Down
47 changes: 47 additions & 0 deletions test/specs-src/data.future.es6
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,53 @@ const { _ExecutionState, _Deferred: Deferred } = Future;
const { Resolved, Rejected } = _ExecutionState;

describe('Data.Future', function() {
describe('conversions', () => {
property('Promise.resolve(v) → Future.resolve(v)', 'nat', (a) => {
return new Promise((ok, error) => {
Future.fromPromise(Promise.resolve(a)).listen({
onResolved: (v) => v === a ? ok(true) : error(`Assertion failed: ${a} === ${v}`),
onRejected: (v) => error(`Expected a resolved future with ${a}, got a rejected future with ${v}`),
onCancelled: () => error(`Expected a resolved future with ${a}, got a cancelled future`)
});
});
});

property('Promise.reject(v) → Future.reject(v)', 'nat', (a) => {
return new Promise((ok, error) => {
Future.fromPromise(Promise.reject(a)).listen({
onRejected: (v) => v === a ? ok(true) : error(`Assertion failed: ${a} === ${v}`),
onResolved: (v) => error(`Expected a rejected future with ${a}, got a resolved future with ${v}`),
onCancelled: () => error(`Expected a rejected future with ${a}, got a cancelled future`)
});
});
});

property('Promise.reject(Cancelled()) → Future.cancel()', () => {
return new Promise((ok, error) => {
Future.fromPromise(Promise.reject(_ExecutionState.Cancelled())).listen({
onRejected: (v) => error(`Expected a cancelled future, got a rejected future with ${v}`),
onResolved: (v) => error(`Expected a cancelled future, got a resolved future with ${v}`),
onCancelled: () => ok(true)
});
});
});

property('Future.of(v) → Promise.resolve(v)', 'nat', async (a) => {
return (await Future.of(a).toPromise()) === a;
});

property('Future.rejected(v) → Promise.reject(v)', 'nat', async (a) => {
return await Future.rejected(a).toPromise().catch(v => v === a);
});

property('Future.cancel() → Promise.reject(Cancelled())', async () => {
const deferred = new Deferred();
deferred.cancel();
return await deferred.future().toPromise().catch(v => _ExecutionState.Cancelled.hasInstance(v));
});
});


describe('Deferreds', function() {
it('new Deferred() should start in a pending state', () => {
let deferred = new Deferred();
Expand Down