diff src/implab/safe.js @ 7:9c0943c68a90

minor fixes added safe.async(fn, thisArg)
author cin
date Tue, 20 Jun 2017 19:45:15 +0300
parents 00779cb63b12
children f0035923ff3e
line wrap: on
line diff
--- a/src/implab/safe.js	Tue Jun 20 00:33:15 2017 +0300
+++ b/src/implab/safe.js	Tue Jun 20 19:45:15 2017 +0300
@@ -138,6 +138,52 @@
                 return dest;
             },
 
+            /** Wraps the specified function to emulate an asynchronous execution.
+             * @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
+             * @param{Function|String} fn [Required] Function wich will be wrapped.
+             */
+            async: function (fn, thisArg) {
+                if (arguments.length == 2)
+                    fn = thisArg[fn];
+
+                if (fn == null)
+                    throw new Error("The function must be specified");
+
+                function wrapresult(x, e) {
+                    if (e) {
+                        return {
+                            then: function (cb, eb) {
+                                try {
+                                    return eb ? wrapresult(eb(e)) : this;
+                                } catch (e2) {
+                                    return wrapresult(null, e2);
+                                }
+                            }
+                        };
+                    } else {
+                        if (x && x.then)
+                            return x;
+                        return {
+                            then : function(cb) {
+                                try {
+                                    return cb ? wrapresult(cb(x)) : this;
+                                } catch(e2) {
+                                    return wrapresult(e2);
+                                }
+                            }
+                        };
+                    }
+                }
+
+                return /** @this */ function () {
+                    try {
+                        return wrapresult(fn.apply(this, arguments));
+                    } catch (e) {
+                        return wrapresult(null, e);
+                    }
+                };
+            },
+
             create: function () {
                 if (console && console.warn)
                     console.warn("implab/safe::create is deprecated use Object.create instead");