promisify.js 656 B

12345678910111213141516171819202122
  1. // cannot use fat arrow function since we don't get the arguments, then
  2. const promisify = (fn, context = null) => function () {
  3. // copy passed arguments to a new array
  4. const args = toArray(arguments);
  5. return new Promise((resolve, reject) => {
  6. // add a callback to the arguments, which resolves the promise with the result
  7. args.push((err, data) => {
  8. if (err) {
  9. reject(err);
  10. } else {
  11. resolve(data);
  12. }
  13. });
  14. // call the original function with our callback flavoured arguments
  15. fn.apply(context, args);
  16. });
  17. };
  18. export default promisify;