How to use promise-retry - 10 common examples

To help you get started, we’ve selected a few promise-retry examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github flow-typed / flow-typed / definitions / npm / promise-retry_v1.1.x / flow_v0.45.x-v0.103.x / test_promise-retry.js View on Github external
promiseRetry(promiseFn).then(function (str: string) { console.log(str); });

promiseRetry(promiseFn, {
  retries: 1,
  factor: 1,
  minTimeout: 1000,
  maxTimeout: 5000,
  randomize: true,
})
.then(function (str: string) {
  console.log(str);
});

// $ExpectError
promiseRetry(2);

// $ExpectError
promiseRetry(function () { /* noop */ }, {retries: 'banana'});

// $ExpectError
promiseRetry(promiseFn).then(function (num: number) { console.log(num); });
github facebook / flipper / src / utils / adbClient.tsx View on Github external
).catch(err => {
    console.error(
      'Failed to create adb client using shell adb command. Trying with adbkit.\n' +
        err.toString(),
    );

    /* In the event that starting adb with the above method fails, fallback
         to using adbkit, though its known to be unreliable. */
    const unsafeClient: Client = adbkit.createClient(adbConfig());
    return reportPlatformFailures<Client>(
      promiseRetry<Client>(
        (retry, attempt): Promise<Client> => {
          return unsafeClient
            .listDevices()
            .then(() => {
              return unsafeClient;
            })
            .catch((e: Error) => {
              console.warn(
                `Failed to start adb client. Retrying. ${e.message}`,
              );
              if (attempt <= MAX_RETRIES) {
                retry(e);
              }
              throw e;
            });
        },
github uber / streetscape.gl / modules / core / src / utils / request-utils.js View on Github external
const cacheUrl = uriOptions.uri;
  if (defeatBrowserCache) {
    uriOptions.uri = addParametersToUrl(uriOptions.uri, `noCache=${Date.now()}`);
  }

  // If this resource has already been requested, just return the same promise
  let promise = requestCache[cacheUrl];
  if (promise) {
    // console.log(`request serving promise from cache ${cacheUrl}`); // eslint-disable-line
    // Remove promise from cache to enable response to be garbage collected
    requestCache[cacheUrl] = null;
    return promise;
  }

  promise = PromiseRetry(
    retry => {
      return promisifiedRequest(requestFunction, uriOptions, retries).catch(retry);
    },
    {
      retries,
      minTimeout: 200,
      randomize: true
    }
  );

  // Add the new promise to the request cache (if requested)
  if (useLocalCache) {
    // console.log(`request saving promise in cache ${cacheUrl}`); // eslint-disable-line
    requestCache[cacheUrl] = requestCache[cacheUrl] || promise;
  }
github radixdlt / radixdlt-js / src / modules / universe / RadixUniverse.ts View on Github external
private loadPeersFromBootstrap() {
        // const bootstrapNodesLenght = (this.nodeDiscovery as RadixNodeDiscoveryHardcoded).bootstrapNodes.length;
        // if(bootstrapNodesLenght > 1)
        //     throw new Error('not cool ' + bootstrapNodesLenght)
        return promiseRetry(
            async (retry, attempt) => {
                try {
                    this.liveNodes = await this.nodeDiscovery.loadNodes()
                    this.lastNetworkUpdate = Date.now()
                    return this.liveNodes
                } catch (error) {
                    logger.error(error)
                    retry()
                }
            },
            {
                retries: 1000,
                maxtimeout: 60000,
            },
        )
    }
github creditsenseau / zeebe-client-node-js / src / zb / ZBClient.ts View on Github external
private async retryOnFailure<T>(
		operation: () => Promise<T>,
		retries = this.maxRetries
	): Promise<T> {
		const c = console
		return promiseRetry(
			(retry, n) => {
				if (this.closing) {
					return Promise.resolve() as any
				}
				if (n > 1) {
					c.error(
						`gRPC connection is in failed state. Attempt ${n}. Retrying in 5s...`
					)
				}
				return operation().catch(err => {
					// This could be DNS resolution, or the gRPC gateway is not reachable yet
					const isNetworkError =
						err.message.indexOf('14') === 0 ||
						err.message.indexOf('Stream removed') !== -1
					if (isNetworkError) {
						c.error(`${err.message}`)
github lmachens / meteor-apm-server / kadira-ui / server / alertsman / server / messenger.js View on Github external
_sendEmail(address, subject, message) {
    if (this.loggingOnly) {
      info(`Sending Email: to=${address} subject=${subject}`);
      return Promise.resolve(true);
    }

    const mailOptions = {
      from: 'Kadira Alerts <alerts-noreply@kadira.io>',
      to: address,
      subject,
      text: fromString(message),
      html: message
    };

    let retryPromise = promiseRetry(retry => {
      try {
        Fiber(() => {
          return Email.send(mailOptions);
        }).run();
        } catch(error) {
          retry(error);
        };
      }, retryOptions);

    return retryPromise
    .catch(err => {
      error(`Sending email failed: ${err.stack}`);
    });
  }
github goodeggs / json-fetch / src / index.js View on Github external
async function retryFetch (requestUrl: string, jsonFetchOptions: JsonFetchOptions): Promise<Response> {
  const shouldRetry = jsonFetchOptions.shouldRetry || DEFAULT_SHOULD_RETRY;
  const retryOptions = Object.assign({}, DEFAULT_RETRY_OPTIONS, jsonFetchOptions.retry);
  const requestOptions = getRequestOptions(jsonFetchOptions);
  try {
    const response = await promiseRetry(async (throwRetryError, retryCount) => {
      try {
        const res = await fetch(requestUrl, requestOptions);
        if (shouldRetry(res))
          throwRetryError();
        return res;
      } catch (err) {
        err.retryCount = retryCount ? retryCount - 1 : 0;
        if (err.code !== 'EPROMISERETRY' && shouldRetry(err))
          throwRetryError(err);
        throw err;
      }
    }, retryOptions);
    return response;
  } catch (err) {
    err.name = 'FetchError';
    throw err;
github vitalybe / radio-stream / web / app / utils / retries.js View on Github external
promiseRetry(promiseReturningFunc) {
    let logger = loggerCreator(this.promiseRetry.name, moduleLogger);
    let lastError = null;

    return promiseRetryLib((retry, number) => {
      logger.info(`start. try number: ${number}`);

      return promiseReturningFunc(lastError).catch(err => {
        logger.warn(`promise failed... retrying: ${err}`);
        lastError = err;

        retry(err);
      })
    }, {retries: 1000})
  }
}
github prymitive / karma / ui / src / Common / Fetch.js View on Github external
const FetchGet = async (uri, options, beforeRetry) =>
  await promiseRetry(
    (retry, number) =>
      fetch(
        uri,
        merge(
          {},
          {
            method: "GET"
          },
          CommonOptions,
          {
            mode: number <= FetchRetryConfig.retries ? "cors" : "no-cors"
          },
          options
        )
      ).catch(err => {
        beforeRetry && beforeRetry(number);
github moneyhub / navy / packages / navy / src / navy / index.js View on Github external
async waitForHealthy(
    services?: Array<string>,
    progressCallback?: Function,
    retryConfig?: RetryConfig = {factor: 1.1, retries: 30, minTimeout: 200}
  ): Promise<boolean> {
    if (services == null) {
      services = (await this.ps())
        .filter(service => service && service.raw && service.raw.State.Health)
        .map(service => service.name)
    }

    try {
      await retryPromise(
        retryConfig,
        async (retry) => {
          const ps = await this.ps()

          const specifiedServices = ps
            .filter(service => services && services.indexOf(service.name) !== -1)

          const servicesWithoutHealthInfo = specifiedServices
            .filter(service => !service.raw || !service.raw.State.Health)
            .map(service => service.name)

          if (servicesWithoutHealthInfo.length > 0) {
            throw new NavyError('The specified services don\'t have health checks: ' + servicesWithoutHealthInfo.join(', '))
          }

          const serviceHealth = specifiedServices.map(service => ({

promise-retry

Retries a function that returns a promise, leveraging the power of the retry module.

MIT
Latest version published 2 years ago

Package Health Score

71 / 100
Full package analysis

Popular promise-retry functions