Last active
August 29, 2020 04:51
-
-
Save GitaiQAQ/810fec3e7164536d2aa7e103d4fbe891 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const doThis = count => Array.prototype.map.bind(Array.from({ length: count })); | |
| export const Timeout = (timeout, promise?: Promise<any>) => | |
| new Promise((resolve, reject) => { | |
| const timer = setTimeout(() => { | |
| reject(new Error(`Timeout(${timeout})`)); | |
| }, timeout); | |
| // 如果完成了得清理 | |
| const clear = () => clearTimeout(timer); | |
| promise.then(clear, clear); | |
| }); | |
| export const Reduce = (promises, initialValue, timeout?: number) => { | |
| if (!Array.isArray(promises)) return Promise.resolve(new Error('promises is not Array')); | |
| const promise = new Promise((resolve, reject) => { | |
| function handle(task, prevValue) { | |
| return (timer ? Promise.race([timer, Promise.resolve(task(prevValue))]) : Promise.resolve(task(prevValue))) | |
| .then((data) => { | |
| if (promises.length) { | |
| return handle(promises.shift(), data); | |
| } | |
| return resolve(data); | |
| }) | |
| .catch(reject); | |
| } | |
| return Promise.resolve().then(() => handle(promises.shift(), initialValue)); | |
| }); | |
| const timer = timeout && Timeout(timeout, promise); | |
| // 超时 | |
| return timer ? Promise.race([timer, promise]) : promise; | |
| }; | |
| Reduce(doThis(PING_COUNT)((_, index) => (prevData) => { | |
| return pingPromise(this.url).then(data => { | |
| const latencySum = prevData + data.end - data.start; | |
| this.realTimeLatency = latencySum / (index + 1); | |
| return latencySum; | |
| }); | |
| }), 0, 1).then((latencySum: number) => { | |
| return latencySum / PING_COUNT; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment