Sync.js
2.23 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var DLList, Sync;
DLList = require("./DLList");
Sync = class Sync {
constructor(name, Promise) {
this.schedule = this.schedule.bind(this);
this.name = name;
this.Promise = Promise;
this._running = 0;
this._queue = new DLList();
}
isEmpty() {
return this._queue.length === 0;
}
_tryToRun() {
var _this = this;
return _asyncToGenerator(function* () {
var args, cb, error, reject, resolve, returned, task;
if (_this._running < 1 && _this._queue.length > 0) {
_this._running++;
var _this$_queue$shift = _this._queue.shift();
task = _this$_queue$shift.task;
args = _this$_queue$shift.args;
resolve = _this$_queue$shift.resolve;
reject = _this$_queue$shift.reject;
cb = yield _asyncToGenerator(function* () {
try {
returned = yield task(...args);
return function () {
return resolve(returned);
};
} catch (error1) {
error = error1;
return function () {
return reject(error);
};
}
})();
_this._running--;
_this._tryToRun();
return cb();
}
})();
}
schedule(task, ...args) {
var promise, reject, resolve;
resolve = reject = null;
promise = new this.Promise(function (_resolve, _reject) {
resolve = _resolve;
return reject = _reject;
});
this._queue.push({
task,
args,
resolve,
reject
});
this._tryToRun();
return promise;
}
};
module.exports = Sync;