Last active
February 24, 2017 15:30
-
-
Save gerrard00/c682e62ac32c6156d2504a3f86fb6722 to your computer and use it in GitHub Desktop.
Adds a promise property to a callback function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// the wrapper | |
function addPromiseToCallback(fn) { | |
const result = function result(err, data) { | |
fn(err, data); | |
if (err) { | |
result.reject(err); | |
return; | |
} | |
result.resolve(data); | |
}; | |
result.promise = new Promise((resolve, reject) => { | |
result.resolve = resolve; | |
result.reject = reject; | |
}); | |
return result; | |
} | |
// calls the callback | |
function myLamdaFunction(cb) { | |
setTimeout(() => cb(null, Date.now()), 100); | |
} | |
// calls the callback with error | |
function myLamdaFunctionWithError(cb) { | |
setTimeout(() => cb(new Error('some error'), null), 100); | |
} | |
// my callback function | |
function myCallback(arg1, arg2) { | |
console.log(`called back! ${arg1}, ${arg2}`); | |
} | |
const callbackWithPromise = addPromiseToCallback(myCallback); | |
myLamdaFunction(callbackWithPromise); | |
// myLamdaFunctionWithError(callbackWithPromise); | |
callbackWithPromise.promise | |
.then((data) => { | |
console.log(`Promise 1 resolved with ${data}`); | |
}) | |
.catch(err => console.error(`Rejected with ${err}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this to help test an AWS lambda function. Then I realized I could have just used a promisify library to turn my lambda function into a promise. Oh well, fun anyway.