Promise
Observable
Promise 不是为了处理 “重试” 逻辑。如果你想这样做,你应该调查一下 的 观测 强> 使用 rxjs 图书馆 。这将允许您在捕获错误时使用任意时间间隔重试。
rxjs
const { from, interval, of } = rxjs; const { catchError, mergeMap, tap, skipWhile, take } = rxjs.operators; const THRESHOLD = 3; const RETRY_INTERVAL = 1000; // Equivalent to 'amqp.connect' const functionThatThrows = number => number < THRESHOLD ? Promise.reject(new Error("ERROR")) : Promise.resolve("OK"); // Equivalent to `getConnect` const getConnect = () => interval(RETRY_INTERVAL) .pipe( mergeMap(x => from(functionThatThrows(x)).pipe(catchError(e => of(e)))), skipWhile(x => { const isError = x instanceof Error; if (isError) console.log('Found error. Retrying...'); return isError; }), take(1) ).toPromise(); // Resolve only if the inner Promise is resolved getConnect().then(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
interval
1000
amqp.connect
functionThatThrows
catchError
take(1)
toPromise
then
如果你只想保持连接,直到建立连接,你可以包装 getConnect 方法成新 keepConnect 方法:
getConnect
keepConnect
keepConnect = async () => { while (true) { try { let conn = await getConnect() return conn } catch (e) {} } }
但是我觉得通过改变它来实现类似“尝试连接n次”的东西会更好 while 条件。一般来说,“while true”解决方案不干净并且可能表现不佳,存在降低事件循环速度的风险(假设连接方法总是在几毫秒内返回错误)。
while
您还可以使用。在连接尝试之间实现渐进式延迟系统 keepConnect 包装作为想法。
如果您想在连接丢失时重新连接,那么这与Rabbit(我不知道)和他的事件有关。