Debian Codegraph @

deferred/ext/function/call-async.js

raw
1 // Call asynchronous function
2
3 "use strict";
4
5 var toArray = require("es5-ext/array/to-array")
6 , isValue = require("es5-ext/object/is-value")
7 , callable = require("es5-ext/object/valid-callable")
8 , deferred = require("../../deferred")
9 , isPromise = require("../../is-promise")
10 , processArguments = require("../_process-arguments");
11
12 var slice = Array.prototype.slice, apply = Function.prototype.apply, applyFn, callAsync;
13
14 applyFn = function (fn, args, def) {
15 args = toArray(args);
16 apply.call(
17 fn,
18 this,
19 args.concat(function (error, result) {
20 if (isValue(error)) def.reject(error);
21 else def.resolve(arguments.length > 2 ? slice.call(arguments, 1) : result);
22 })
23 );
24 };
25
26 callAsync = function (fn, length, context, args) {
27 var def;
28 args = processArguments(args, length);
29 if (isPromise(args)) {
30 if (args.failed) return args;
31 def = deferred();
32 args.done(function (resolvedArgs) {
33 if (fn.returnsPromise) {
34 apply.call(fn, context, resolvedArgs);
35 return;
36 }
37 try { applyFn.call(context, fn, resolvedArgs, def); } catch (e) { def.reject(e); }
38 }, def.reject);
39 return def.promise;
40 }
41 if (fn.returnsPromise) return apply.call(fn, context, args);
42 def = deferred();
43 try {
44 applyFn.call(context, fn, args, def);
45 } catch (e) {
46 def.reject(e);
47 throw e;
48 }
49 return def.promise;
50 };
51
52 module.exports = exports = function (context/*, …args*/) {
53 return callAsync(callable(this), null, context, slice.call(arguments, 1));
54 };
55
56 Object.defineProperty(exports, "_base", {
57 configurable: true,
58 enumerable: false,
59 writable: true,
60 value: callAsync
61 });