From 4e31a39d35635251e8680301dccf7d186396f739 Mon Sep 17 00:00:00 2001 From: Marcel Laverdet Date: Wed, 24 Feb 2016 19:49:38 -0600 Subject: [PATCH] Utility functions for converting to/from Promises These functions will make interoperating with existing async libraries much easier. Also bump npm version -> 1.0.10 --- README.md | 6 ++++++ future.js | 29 +++++++++++++++++++++++++++++ package.json | 2 +- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 97dc225..cde33eb 100644 --- a/README.md +++ b/README.md @@ -534,6 +534,12 @@ Future.prototype.proxy = function(future) { ... } * future threw, future.wait() will throw. */ Future.prototype.wait = function() { ... } + +/** + * Support for converting a Future to and from ES6 Promises. + */ +Future.fromPromise = function(promise) { ... } +Future.prototype.promise = function() { ... } ``` GARBAGE COLLECTION diff --git a/future.js b/future.js index dc8948d..48cf7dd 100644 --- a/future.js +++ b/future.js @@ -188,6 +188,19 @@ Future.wait = function wait(/* ... */) { } }; +/** + * Return a Future that waits on an ES6 Promise. + */ +Future.fromPromise = function(promise) { + var future = new Future; + promise.then(function(val) { + future.return(val); + }, function(err) { + future.throw(err); + }); + return future; +}; + Future.prototype = { /** * Return the value of this future. If the future hasn't resolved yet this will throw an error. @@ -408,6 +421,22 @@ Future.prototype = { return this; }, + /** + * Returns an ES6 Promise + */ + promise: function() { + var that = this; + return new Promise(function(resolve, reject) { + that.resolve(function(err, val) { + if (err) { + reject(err); + } else { + resolve(val); + } + }); + }); + }, + /** * Differs from its functional counterpart in that it actually resolves the future. Thus if the * future threw, future.wait() will throw. diff --git a/package.json b/package.json index 03a129a..602907f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fibers", - "version": "1.0.9", + "version": "1.0.10", "description": "Cooperative multi-tasking for Javascript", "keywords": [ "fiber", "fibers", "coroutine", "thread", "async", "parallel", "worker", "future", "promise"],