ravendb
Version:
RavenDB client for Node.js
130 lines • 3.59 kB
JavaScript
import { getError } from "../Exceptions/index.js";
export async function raceToResolution(promises, onErrorCallback) {
// There is no way to know which promise is rejected.
// So we map it to a new promise to return the index when it fails
const indexPromises = promises.map((p, index) => p.catch(() => {
throw index;
}));
try {
return await Promise.race(indexPromises);
}
catch (index) {
// The promise has rejected, remove it from the list of promises and just continue the race.
const p = promises.splice(index, 1)[0];
p.catch(err => {
if (onErrorCallback) {
onErrorCallback(err);
}
});
return raceToResolution(promises);
}
}
export function defer() {
let resolve;
let reject;
let isFulfilled = false;
const promise = new Promise(function (res, rej) {
resolve = v => {
isFulfilled = true;
res(v);
};
reject = rej;
});
return {
resolve,
reject,
promise,
isFulfilled
};
}
export async function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export async function wrapWithTimeout(promise, ms) {
let timeoutHandle;
const error = getError("TimeoutException", `Timeout after ${ms} ms.`);
const timeoutPromise = new Promise((resolve) => {
timeoutHandle = setTimeout(() => {
resolve(error);
}, ms);
});
try {
const raceWinner = await Promise.race([promise, timeoutPromise]);
if (raceWinner === error) {
// timeout win
throw raceWinner;
}
else {
// cancel existing timeout
clearTimeout(timeoutHandle);
return raceWinner;
}
}
catch (e) {
clearTimeout(timeoutHandle);
throw e;
}
}
export class AsyncTimeout {
get promise() {
return this._promise;
}
get timedOut() {
return this._timedOut;
}
_timedOut = false;
_timer;
_promise;
_op;
_resolve;
_reject;
constructor(ms, op) {
this._op = op;
this._promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
this._timer = setTimeout(() => {
this._timedOut = true;
this._reject(this._getTimeoutError(ms));
}, ms);
}
_getTimeoutError(ms) {
const opText = this._op ? `Operation '${this._op}'` : `Operation`;
const timeoutError = getError("TimeoutError", `${opText} timed out after ${ms} ms.`);
return timeoutError;
}
cancel() {
if (this._timer) {
clearTimeout(this._timer);
}
this._resolve();
}
}
export class PromiseStatusTracker {
_status;
_promise;
constructor(promise) {
if (!promise) {
throw new Error("Promise to track cannot be null.");
}
this._status = "PENDING";
this._promise = promise;
this._promise
.then(() => this._status = "RESOLVED")
.catch(() => this._status = "REJECTED");
}
static track(promise) {
return new PromiseStatusTracker(promise);
}
isFullfilled() {
return this._status === "REJECTED" || this._status === "RESOLVED";
}
isResolved() {
return this._status === "RESOLVED";
}
isRejected() {
return this._status === "REJECTED";
}
}
//# sourceMappingURL=PromiseUtil.js.map