Debian Codegraph @

deferred/ext/promise/cb.js

raw
1 // 'cb' - Promise extension
2 //
3 // promise.cb(cb)
4 //
5 // Handles asynchronous function style callback (which is run in next event loop
6 // the earliest). Returns self promise. Callback is optional.
7 //
8 // Useful when we want to configure typical asynchronous function which logic is
9 // internally configured with promises.
10 //
11 // Extension can be used as follows:
12 //
13 // var foo = function (arg1, arg2, cb) {
14 // var d = deferred();
15 // // ... implementation
16 // return d.promise.cb(cb);
17 // };
18 //
19 // `cb` extension returns promise and handles eventual callback (optional)
20
21 "use strict";
22
23 var isValue = require("es5-ext/object/is-value")
24 , callable = require("es5-ext/object/valid-callable")
25 , nextTick = require("next-tick")
26 , deferred = require("../../deferred");
27
28 deferred.extend(
29 "cb",
30 function (cb) {
31 if (!isValue(cb)) return this;
32 callable(cb);
33 nextTick(
34 function () {
35 if (this.resolved) {
36 if (this.failed) cb(this.value);
37 else cb(null, this.value);
38 } else {
39 if (!this.pending) this.pending = [];
40 this.pending.push("cb", [cb]);
41 }
42 }.bind(this)
43 );
44 return this;
45 },
46 function (cb) {
47 if (this.failed) cb(this.value);
48 else cb(null, this.value);
49 },
50 function (cb) {
51 if (!isValue(cb)) return this;
52 callable(cb);
53 nextTick(
54 function () {
55 if (this.failed) cb(this.value);
56 else cb(null, this.value);
57 }.bind(this)
58 );
59 return this;
60 }
61 );