forked from chanind/hanzi-writer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoadingManager.js
58 lines (50 loc) · 1.8 KB
/
LoadingManager.js
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
const { callIfExists } = require('./utils');
function LoadingManager(options) {
this._loadCounter = 0;
this._options = options;
this._isLoading = false;
// use this to attribute to determine if there was a problem with loading
this.loadingFailed = false;
}
LoadingManager.prototype._debouncedLoad = function(char, count) {
// these wrappers ignore all responses except the most recent.
const wrappedResolve = (data) => {
if (count === this._loadCounter) this._resolve(data);
};
const wrappedReject = (reason) => {
if (count === this._loadCounter) this._reject(reason);
};
const returnedData = this._options.charDataLoader(char, wrappedResolve, wrappedReject);
if (returnedData) wrappedResolve(returnedData);
};
LoadingManager.prototype._setupLoadingPromise = function() {
return new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
}).then((data) => {
this._isLoading = false;
callIfExists(this._options.onLoadCharDataSuccess, data);
return data;
}, (reason) => {
this._isLoading = false;
this.loadingFailed = true;
callIfExists(this._options.onLoadCharDataError, reason);
// If error callback wasn't provided, throw an error so the developer will be aware something went wrong
if (!this._options.onLoadCharDataError) {
if (reason instanceof Error) throw reason;
const err = new Error(`Failed to load char data for ${this._loadingChar}`);
err.reason = reason;
throw err;
}
});
};
LoadingManager.prototype.loadCharData = function(char) {
this._loadingChar = char;
const promise = this._setupLoadingPromise();
this.loadingFailed = false;
this._isLoading = true;
this._loadCounter++;
this._debouncedLoad(char, this._loadCounter);
return promise;
};
module.exports = LoadingManager;