signal-desktop/ts/textsecure/TaskWithTimeout.ts
Scott Nonnenberg b7d56def82 Moves libtextsecure to Typescript
* Starting to work through lint errors

* libsignal-protocol: Update changes for primary repo compatibility

* Step 1: task_with_timeout rename

* Step 2: Apply the changes to TaskWithTimeout.ts

* Step 1: All to-be-converted libtextsecure/*.js files moved

* Step 2: No Typescript errors!

* Get libtextsecure tests passing again

* TSLint errors down to 1

* Compilation succeeds, no lint errors or test failures

* WebSocketResources - update import for case-sensitive filesystems

* Fixes for lint-deps

* Remove unnecessary @ts-ignore

* Fix inability to message your own contact after link

* Add log message for the end of migration 20

* lint fix
2020-04-15 14:45:11 -07:00

78 lines
1.7 KiB
TypeScript

// tslint:disable no-default-export
export default function createTaskWithTimeout(
task: () => Promise<any>,
id: string,
options: { timeout?: number } = {}
) {
const timeout = options.timeout || 1000 * 60 * 2; // two minutes
const errorForStack = new Error('for stack');
return async () =>
new Promise((resolve, reject) => {
let complete = false;
let timer: any = setTimeout(() => {
if (!complete) {
const message = `${id ||
''} task did not complete in time. Calling stack: ${
errorForStack.stack
}`;
window.log.error(message);
reject(new Error(message));
return;
}
return null;
}, timeout);
const clearTimer = () => {
try {
const localTimer = timer;
if (localTimer) {
timer = null;
clearTimeout(localTimer);
}
} catch (error) {
window.log.error(
id || '',
'task ran into problem canceling timer. Calling stack:',
errorForStack.stack
);
}
};
const success = (result: any) => {
clearTimer();
complete = true;
resolve(result);
return;
};
const failure = (error: Error) => {
clearTimer();
complete = true;
reject(error);
return;
};
let promise;
try {
promise = task();
} catch (error) {
clearTimer();
throw error;
}
if (!promise || !promise.then) {
clearTimer();
complete = true;
resolve(promise);
return;
}
return promise.then(success, failure);
});
}