From d2f23ada25a9c4e194e57643ca7644beca7394e5 Mon Sep 17 00:00:00 2001 From: "sunny.luo" Date: Tue, 12 Nov 2024 23:59:16 +0800 Subject: [PATCH] fix testurl --- src/client.ts | 11 ++++------- src/utils.ts | 26 +++++++++++++++++++++----- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/client.ts b/src/client.ts index f388d17..37065d7 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,5 +1,5 @@ import { CheckResult, PushyOptions, ProgressData, EventType } from './type'; -import { joinUrls, log, testUrls } from './utils'; +import { emptyObj, joinUrls, log, noop, promiseAny, testUrls } from './utils'; import { EmitterSubscription, Platform } from 'react-native'; import { PermissionsAndroid } from './permissions'; import { @@ -24,9 +24,6 @@ const defaultServer = { ], }; -const empty = {}; -const noop = () => {}; - if (Platform.OS === 'web') { console.warn('react-native-update 不支持 web 端热更,不会执行操作'); } @@ -230,7 +227,7 @@ export class Pushy { const backupEndpoints = await this.getBackupEndpoints(); if (backupEndpoints) { try { - resp = await Promise.race( + resp = await promiseAny( backupEndpoints.map(endpoint => fetch(this.getCheckUrl(endpoint), fetchPayload), ), @@ -248,7 +245,7 @@ export class Pushy { message: 'Can not connect to update server. Please check your network.', }); this.throwIfEnabled(new Error('errorChecking')); - return this.lastRespJson ? await this.lastRespJson : empty; + return this.lastRespJson ? await this.lastRespJson : emptyObj; } this.lastRespJson = resp.json(); @@ -273,7 +270,7 @@ export class Pushy { } if (server.queryUrls) { try { - const resp = await Promise.race( + const resp = await promiseAny( server.queryUrls.map(queryUrl => fetch(queryUrl)), ); const remoteEndpoints = await resp.json(); diff --git a/src/utils.ts b/src/utils.ts index ff05a47..d456f72 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -4,7 +4,25 @@ export function log(...args: any[]) { console.log('pushy: ', ...args); } -const noop = () => {}; +export function promiseAny(promises: Promise[]) { + return new Promise((resolve, reject) => { + let count = 0; + + promises.forEach(promise => { + Promise.resolve(promise) + .then(resolve) + .catch(() => { + count++; + if (count === promises.length) { + reject(new Error('All promises were rejected')); + } + }); + }); + }); +} + +export const emptyObj = {}; +export const noop = () => {}; class EmptyModule { constructor() { return new Proxy(this, { @@ -23,9 +41,7 @@ const ping = Promise.race([ fetch(url, { method: 'HEAD', - }) - .then(({ status }) => (status === 200 ? url : null)) - .catch(() => null), + }).then(({ status }) => (status === 200 ? url : null)), new Promise(r => setTimeout(() => r(null), 2000)), ]); @@ -44,5 +60,5 @@ export const testUrls = async (urls?: string[]) => { if (await canUseGoogle) { return urls[0]; } - return Promise.race(urls.map(ping)).catch(() => null); + return promiseAny(urls.map(ping)).catch(() => null); };