summaryrefslogtreecommitdiff
path: root/lib/asyncify.js
diff options
context:
space:
mode:
authorAlex Early <alexander.early@gmail.com>2018-07-08 16:58:36 -0700
committerGitHub <noreply@github.com>2018-07-08 16:58:36 -0700
commite4751178540a3c6e64598b93977481ec599704d2 (patch)
treedce5731bdb1076971d2e4a0a42fbe0d95c720185 /lib/asyncify.js
parent6405b109fe60541ff42d7638ac891d321d6a7bb3 (diff)
downloadasync-e4751178540a3c6e64598b93977481ec599704d2.tar.gz
ES6-ify codebase (#1553)
* cancelable foreach * cancelable waterfall * cancellable auto * fix lint * fix tests * cancelable whilst/until/during/forever * fix waterfall test. It WILL get there * docs * use rest params instead of slice * clean up internals * remove property func * clarify uses of createTester * happy path async funtions in asyncify * stop using arguments * DLL to class * moar arrows * fix merge issues * remove forOwn * moar arrows * fix merge mistake * even more arrows, what can stop him * mo more fn.apply(null,...) * remove more spurious uses of apply * update lint config * just when you thought there couldn't possibly be more arrows * use eslint:recommended * even less uses or aguments * get rid of prototype cuteness * fix concat tests * fix more tests
Diffstat (limited to 'lib/asyncify.js')
-rw-r--r--lib/asyncify.js31
1 files changed, 20 insertions, 11 deletions
diff --git a/lib/asyncify.js b/lib/asyncify.js
index e6d63c0..168f88a 100644
--- a/lib/asyncify.js
+++ b/lib/asyncify.js
@@ -1,5 +1,6 @@
import initialParams from './internal/initialParams';
import setImmediate from './internal/setImmediate';
+import { isAsync } from './internal/wrapAsync'
/**
* Take a sync function and make it async, passing its return value to a
@@ -58,6 +59,14 @@ import setImmediate from './internal/setImmediate';
* q.push(files);
*/
export default function asyncify(func) {
+ if (isAsync(func)) {
+ return function (...args/*, callback*/) {
+ const callback = args.pop()
+ const promise = func.apply(this, args)
+ return handlePromise(promise, callback)
+ }
+ }
+
return initialParams(function (args, callback) {
var result;
try {
@@ -67,25 +76,25 @@ export default function asyncify(func) {
}
// if result is Promise object
if (result && typeof result.then === 'function') {
- result.then(function(value) {
- invokeCallback(callback, null, value);
- }, function(err) {
- invokeCallback(callback, err.message ? err : new Error(err));
- });
+ return handlePromise(result, callback)
} else {
callback(null, result);
}
});
}
+function handlePromise(promise, callback) {
+ return promise.then(value => {
+ invokeCallback(callback, null, value);
+ }, err => {
+ invokeCallback(callback, err.message ? err : new Error(err));
+ });
+}
+
function invokeCallback(callback, error, value) {
try {
callback(error, value);
- } catch (e) {
- setImmediate(rethrow, e);
+ } catch (err) {
+ setImmediate(e => { throw e }, err);
}
}
-
-function rethrow(error) {
- throw error;
-}