forked from signalapp/Signal-Desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask_with_timeout.js
71 lines (65 loc) · 2.35 KB
/
task_with_timeout.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
/*
* vim: ts=4:sw=4:expandtab
*/
(function () {
window.textsecure = window.textsecure || {};
window.textsecure.createTaskWithTimeout = function(task, id, options) {
options = options || {};
options.timeout = options.timeout || (1000 * 60 * 2); // two minutes
var errorForStack = new Error('for stack');
return function() {
return new Promise(function(resolve, reject) {
var complete = false;
var timer = setTimeout(function() {
if (!complete) {
var message =
(id || '')
+ ' task did not complete in time. Calling stack: '
+ errorForStack.stack;
console.log(message);
return reject(new Error(message));
}
}.bind(this), options.timeout);
var clearTimer = function() {
try {
var localTimer = timer;
if (localTimer) {
timer = null;
clearTimeout(localTimer);
}
}
catch (error) {
console.log(
id || '',
'task ran into problem canceling timer. Calling stack:',
errorForStack.stack
);
}
};
var success = function(result) {
clearTimer();
complete = true;
return resolve(result);
};
var failure = function(error) {
clearTimer();
complete = true;
return reject(error);
};
var promise;
try {
promise = task();
} catch(error) {
clearTimer();
throw error;
}
if (!promise || !promise.then) {
clearTimer();
complete = true;
return resolve(promise);
}
return promise.then(success, failure);
});
};
};
})();