This repository is currently being migrated. It's locked while the migration is in progress.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncres.js
93 lines (66 loc) · 1.95 KB
/
asyncres.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
define(['underscore'], function (_) {
var AsyncRes = {};
AsyncRes.extend = function (asyncRequest) {
var asyncRes = Object.create(AsyncRes)
// Resource value
asyncRes.res = null;
// Queued callbacks waiting for the resource
asyncRes.queue = [];
// Currenly loading the resource
asyncRes.loading = false;
// Async load resource method
asyncRes.asyncReq = asyncRequest;
return asyncRes;
};
AsyncRes._update = function () {
// Is resource already being requested
if (this.loading) return false;
var inst = this,
handled = false;
this.res = null;
this.loading = true;
this.asyncReq(function (res) {
if (handled) return;
handled = true;
inst.loading = false;
inst._setRes(res);
}, function (err) {
if (handled) return;
handled = true;
inst.loading = false;
inst._handleError(err);
});
};
AsyncRes._setRes = function (res) {
this.res = res;
while (this.queue.length > 0) {
this.queue.shift()(null, res);
}
};
/**
* Handles error occurred while loading the resource.
*
* Responds to queued callbacks with the error
* @param {Error} err Error object
*/
AsyncRes._handleError = function (err) {
this.error = err;
// Move callbacks to another array
var queue = this.queue.splice(0, this.queue.length);
while (queue.length > 0) {
queue.shift()(err);
}
};
AsyncRes.set = function (res) {
this.res = res;
};
AsyncRes.get = function (callback) {
if (this.res !== null) {
callback(null, this.res);
} else {
this.queue.push(callback);
this._update();
}
};
return AsyncRes;
});