2019-07-10 10:45:49 +00:00
|
|
|
async function promiseFinally (fn, finalFn) {
|
2018-12-22 21:05:13 +00:00
|
|
|
let result
|
|
|
|
try {
|
|
|
|
if (typeof fn === 'function') {
|
|
|
|
result = await fn()
|
|
|
|
} else {
|
|
|
|
result = await fn
|
|
|
|
}
|
|
|
|
} finally {
|
|
|
|
finalFn()
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
export const timeout = function timeout (fn, ms, msg) {
|
2018-12-22 21:05:13 +00:00
|
|
|
let timerId
|
|
|
|
const warpPromise = promiseFinally(fn, () => clearTimeout(timerId))
|
|
|
|
const timerPromise = new Promise((resolve, reject) => {
|
|
|
|
timerId = setTimeout(() => reject(new Error(msg)), ms)
|
|
|
|
})
|
|
|
|
return Promise.race([warpPromise, timerPromise])
|
|
|
|
}
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
export const waitFor = function waitFor (ms) {
|
2018-12-22 21:05:13 +00:00
|
|
|
return new Promise(resolve => setTimeout(resolve, ms || 0))
|
|
|
|
}
|
2019-01-19 18:14:54 +00:00
|
|
|
export class Timer {
|
2019-07-10 10:45:49 +00:00
|
|
|
constructor () {
|
2019-01-19 18:14:54 +00:00
|
|
|
this._times = new Map()
|
|
|
|
}
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
start (name, description) {
|
2019-01-19 18:14:54 +00:00
|
|
|
const time = {
|
|
|
|
name,
|
|
|
|
description,
|
|
|
|
start: this.hrtime()
|
|
|
|
}
|
|
|
|
this._times.set(name, time)
|
|
|
|
return time
|
|
|
|
}
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
end (name) {
|
2019-01-19 18:14:54 +00:00
|
|
|
if (this._times.has(name)) {
|
|
|
|
const time = this._times.get(name)
|
|
|
|
time.duration = this.hrtime(time.start)
|
|
|
|
this._times.delete(name)
|
|
|
|
return time
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
hrtime (start) {
|
2019-01-19 18:14:54 +00:00
|
|
|
const useBigInt = typeof process.hrtime.bigint === 'function'
|
|
|
|
if (start) {
|
|
|
|
const end = useBigInt ? process.hrtime.bigint() : process.hrtime(start)
|
|
|
|
return useBigInt
|
|
|
|
? (end - start) / BigInt(1000000)
|
|
|
|
: (end[0] * 1e3) + (end[1] * 1e-6)
|
|
|
|
}
|
|
|
|
return useBigInt ? process.hrtime.bigint() : process.hrtime()
|
|
|
|
}
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
clear () {
|
2019-01-19 18:14:54 +00:00
|
|
|
this._times.clear()
|
|
|
|
}
|
|
|
|
}
|