From 4654d15097465aec70a2521db047e77158164003 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Thu, 3 Sep 2020 17:10:07 +0200 Subject: [PATCH] Add `isReadyOrError` when connecting to API (#2577) * Add `isReadyOrError` * lint --- packages/api/src/promise/Api.spec.ts | 2 +- packages/api/src/promise/Api.ts | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/api/src/promise/Api.spec.ts b/packages/api/src/promise/Api.spec.ts index 7080ed27b1..365f6d3886 100644 --- a/packages/api/src/promise/Api.spec.ts +++ b/packages/api/src/promise/Api.spec.ts @@ -97,7 +97,7 @@ describe('ApiPromise', (): void => { } try { - await new ErrorApiPromise().isReady; + await new ErrorApiPromise().isReadyOrError; fail('Expected an error but none occurred.'); } catch { // Pass diff --git a/packages/api/src/promise/Api.ts b/packages/api/src/promise/Api.ts index e226f33d2b..439c779f70 100644 --- a/packages/api/src/promise/Api.ts +++ b/packages/api/src/promise/Api.ts @@ -197,6 +197,7 @@ export function decorateMethod { #isReadyPromise: Promise; + #isReadyOrErrorPromise: Promise; /** * @description Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance. @@ -239,7 +240,13 @@ export default class ApiPromise extends ApiBase<'promise'> { constructor (options?: ApiOptions) { super(options, 'promise', decorateMethod); - this.#isReadyPromise = new Promise((resolve, reject): void => { + this.#isReadyPromise = new Promise((resolve): void => { + super.once('ready', (): void => { + resolve(this); + }); + }); + + this.#isReadyOrErrorPromise = new Promise((resolve, reject): void => { super.once('ready', (): void => { resolve(this); }); @@ -250,12 +257,19 @@ export default class ApiPromise extends ApiBase<'promise'> { } /** - * @description Promise that returns the first time we are connected and loaded + * @description Promise that resolves the first time we are connected and loaded */ public get isReady (): Promise { return this.#isReadyPromise; } + /** + * @description Promise that resolves if we can connect, or reject if there is an error + */ + public get isReadyOrError (): Promise { + return this.#isReadyOrErrorPromise; + } + /** * @description Returns a clone of this ApiPromise instance (new underlying provider connection) */