signal-desktop/libtextsecure/task_with_timeout.js

73 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-07-21 21:51:20 +00:00
/* global window */
/* eslint-disable more/no-then */
// eslint-disable-next-line func-names
2018-05-02 16:51:22 +00:00
(function() {
window.textsecure = window.textsecure || {};
2018-07-21 21:51:20 +00:00
window.textsecure.createTaskWithTimeout = (task, id, options = {}) => {
const timeout = options.timeout || 1000 * 60 * 2; // two minutes
const errorForStack = new Error('for stack');
return () =>
new Promise((resolve, reject) => {
let complete = false;
let timer = setTimeout(() => {
if (!complete) {
const message = `${id ||
''} task did not complete in time. Calling stack: ${
errorForStack.stack
}`;
2018-07-21 21:51:20 +00:00
window.log.error(message);
return reject(new Error(message));
}
2018-07-21 21:51:20 +00:00
return null;
}, timeout);
const clearTimer = () => {
2018-05-02 16:51:22 +00:00
try {
2018-07-21 21:51:20 +00:00
const localTimer = timer;
2018-05-02 16:51:22 +00:00
if (localTimer) {
timer = null;
clearTimeout(localTimer);
}
} catch (error) {
window.log.error(
2018-05-02 16:51:22 +00:00
id || '',
'task ran into problem canceling timer. Calling stack:',
errorForStack.stack
);
}
};
2018-07-21 21:51:20 +00:00
const success = result => {
2018-05-02 16:51:22 +00:00
clearTimer();
complete = true;
return resolve(result);
};
2018-07-21 21:51:20 +00:00
const failure = error => {
2018-05-02 16:51:22 +00:00
clearTimer();
complete = true;
return reject(error);
};
2018-07-21 21:51:20 +00:00
let promise;
2018-05-02 16:51:22 +00:00
try {
promise = task();
} catch (error) {
clearTimer();
throw error;
}
if (!promise || !promise.then) {
clearTimer();
complete = true;
return resolve(promise);
}
2018-05-02 16:51:22 +00:00
return promise.then(success, failure);
});
};
})();