comparison 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
comparison
equal deleted inserted replaced
6:9663631cbdb9 7:9c0943c68a90
134 dest[tmpl[p]] = src[p]; 134 dest[tmpl[p]] = src[p];
135 } 135 }
136 } 136 }
137 } 137 }
138 return dest; 138 return dest;
139 },
140
141 /** Wraps the specified function to emulate an asynchronous execution.
142 * @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
143 * @param{Function|String} fn [Required] Function wich will be wrapped.
144 */
145 async: function (fn, thisArg) {
146 if (arguments.length == 2)
147 fn = thisArg[fn];
148
149 if (fn == null)
150 throw new Error("The function must be specified");
151
152 function wrapresult(x, e) {
153 if (e) {
154 return {
155 then: function (cb, eb) {
156 try {
157 return eb ? wrapresult(eb(e)) : this;
158 } catch (e2) {
159 return wrapresult(null, e2);
160 }
161 }
162 };
163 } else {
164 if (x && x.then)
165 return x;
166 return {
167 then : function(cb) {
168 try {
169 return cb ? wrapresult(cb(x)) : this;
170 } catch(e2) {
171 return wrapresult(e2);
172 }
173 }
174 };
175 }
176 }
177
178 return /** @this */ function () {
179 try {
180 return wrapresult(fn.apply(this, arguments));
181 } catch (e) {
182 return wrapresult(null, e);
183 }
184 };
139 }, 185 },
140 186
141 create: function () { 187 create: function () {
142 if (console && console.warn) 188 if (console && console.warn)
143 console.warn("implab/safe::create is deprecated use Object.create instead"); 189 console.warn("implab/safe::create is deprecated use Object.create instead");