257565db5ec0f6ffafcb8a2340ff6732698e4f0e
[aai/esr-gui.git] /
1 "use strict";
2 module.exports = function(Promise) {
3 var util = require("./util.js");
4 var async = require("./async.js");
5 var tryCatch = util.tryCatch;
6 var errorObj = util.errorObj;
7
8 function spreadAdapter(val, nodeback) {
9     var promise = this;
10     if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
11     var ret =
12         tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
13     if (ret === errorObj) {
14         async.throwLater(ret.e);
15     }
16 }
17
18 function successAdapter(val, nodeback) {
19     var promise = this;
20     var receiver = promise._boundValue();
21     var ret = val === undefined
22         ? tryCatch(nodeback).call(receiver, null)
23         : tryCatch(nodeback).call(receiver, null, val);
24     if (ret === errorObj) {
25         async.throwLater(ret.e);
26     }
27 }
28 function errorAdapter(reason, nodeback) {
29     var promise = this;
30     if (!reason) {
31         var target = promise._target();
32         var newReason = target._getCarriedStackTrace();
33         newReason.cause = reason;
34         reason = newReason;
35     }
36     var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
37     if (ret === errorObj) {
38         async.throwLater(ret.e);
39     }
40 }
41
42 Promise.prototype.asCallback =
43 Promise.prototype.nodeify = function (nodeback, options) {
44     if (typeof nodeback == "function") {
45         var adapter = successAdapter;
46         if (options !== undefined && Object(options).spread) {
47             adapter = spreadAdapter;
48         }
49         this._then(
50             adapter,
51             errorAdapter,
52             undefined,
53             this,
54             nodeback
55         );
56     }
57     return this;
58 };
59 };