浏览代码

[promisify]: simplify via es6 syntax

mightyplow 7 年之前
父节点
当前提交
97e3c06ced
共有 1 个文件被更改,包括 4 次插入16 次删除
  1. 4 16
      src/function/promisify.js

+ 4 - 16
src/function/promisify.js

@@ -3,26 +3,14 @@
  * @param fn
  * @param context
  */
-// cannot use fat arrow function since we don't get the arguments, then
-const promisify = (fn, context = null) => function () {
-
-    // copy passed arguments to a new array
-    const args = toArray(arguments);
-
+const promisify = (fn, context = null) => (...args) => {
     return new Promise((resolve, reject) => {
-        // add a callback to the arguments, which resolves the promise with the result
-        args.push((err, data) => {
-            if (err) {
-                reject(err);
-            } else {
-                resolve(data);
-            }
-        });
+        // create a callback to handle error and data
+        const callback = (err, data) => err ? reject(err) : resolve(data);
 
         // call the original function with our callback flavoured arguments
-        fn.apply(context, args);
+        fn.call(context, ...args, callback);
     });
 };
 
-
 export default promisify;