aboutsummaryrefslogtreecommitdiff
path: root/node_modules/montage/core/promise-queue.js
blob: 87959c5c31fca26d77cf18cfa6ddb5d08ebc4b58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

var Montage = require("./core").Montage;
var Promise = require("./promise").Promise;

exports.PromiseQueue = Montage.create(Montage, {
    init: {
        value: function () {
            this._ends = Promise.defer();
            this._closed = Promise.defer();
            this.closed = this._closed.promise;
            return this;
        }
    },
    put: {
        value: function (value) {
            var next = Promise.defer();
            this._ends.resolve({
                head: value,
                tail: next.promise
            });
            this._ends.resolve = function (resolution) {
                next.resolve(resolution);
            };
        }
    },
    get: {
        value: function () {
            var ends = this._ends;
            var result = ends.promise.get("head");
            this._ends = {
                resolve: function (resolution) {
                    ends.resolve(resolution);
                },
                promise: ends.promise.get("tail")
            };
            return result.fail(function (reason, error, rejection) {
                this._closed.resolve();
                return rejection;
            });
        }
    },
    close: {
        value: function (reason, error, rejection) {
            var end = {
                head: rejection || Promise.reject(reason, error)
            };
            end.tail = end;
            this._ends.resolve(end);
            return this._closed.promise;
        }
    },
    forEach: {
        value: function (put, thisp) {
            var queue = this;
            function loop() {
                return queue.get().then(function (value) {
                    put.call(thisp, value);
                })
                .then(loop);
            }
            return loop();
        }
    }
});