Skip to content

Instantly share code, notes, and snippets.

@gerrard00
Last active February 24, 2017 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerrard00/c682e62ac32c6156d2504a3f86fb6722 to your computer and use it in GitHub Desktop.
Save gerrard00/c682e62ac32c6156d2504a3f86fb6722 to your computer and use it in GitHub Desktop.
Adds a promise property to a callback function
'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}`));
@gerrard00
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment