-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueuer.js
48 lines (40 loc) · 991 Bytes
/
Queuer.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
/**
* Manages requests spam, only will execute one at time.
*
* If more than one request is sent to the caller, it will be queued.
* Only the last request will be stored to be executed latter.
*
*/
var CallQueuer = (function () {
var state = {};
return function caller (call) {
if (!call)
return;
if (state.onCall)
return state.queuedCall = call;
state.onCall = true;
return call().then(function () {
call = state.queuedCall;
state.onCall = false;
state.queuedCall = null;
caller(call);
});
};
})();
/**
* Mocked backend request.
*/
function request () {
return new Promise(function (resolve) {
setTimeout(() => resolve('Request done.'), 1000);
}).then(console.warn);
};
/**
* Secure request spamming.
*/
CallQueuer(request);
CallQueuer(request);
CallQueuer(request);
CallQueuer(request);
CallQueuer(request);
CallQueuer(request);