How to use async-retry - 10 common examples

To help you get started, we’ve selected a few async-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 zeit / now / download / src / index.js View on Github external
onDeath(() => {
    fs.writeFileSync(
      now,
      '#!/usr/bin/env node\n' +
        'console.log("The \'now\' installation did not complete successfully.")\n' +
        'console.log("Please run \'npm i -g now\' to reinstall!")\n'
    );
    process.exit();
  });

  info('For the source code, check out: https://github.com/zeit/now-cli');

  // Print an empty line
  console.log('');

  await retry(
    async () => {
      enableProgress('Downloading Now CLI ' + packageJSON.version);
      showProgress(0);

      try {
        const name = platformToName[platform];
        const url = `https://github.com/zeit/now-cli/releases/download/${packageJSON.version}/${name}.gz`;
        const resp = await fetch(url, { compress: false });

        if (resp.status !== 200) {
          throw new Error(resp.statusText + ' ' + url);
        }

        const size = resp.headers.get('content-length');
        const ws = fs.createWriteStream(partial);
github zeit / now / packages / now-build-utils / src / file-ref.ts View on Github external
url = this.mutable
        ? `https://now-files.s3.amazonaws.com/${digestHash}`
        : `https://dmmcy0pwk6bqi.cloudfront.net/${digestHash}`;
    } else if (digestType === 'sha+ephemeral') {
      // This URL is currently only used for cache files that constantly
      // change. We shouldn't cache it on CloudFront because it'd always be a
      // MISS.
      url = `https://now-ephemeral-files.s3.amazonaws.com/${digestHash}`;
    } else {
      throw new Error('Expected digest to be sha');
    }

    await semaToDownloadFromS3.acquire();
    // console.time(`downloading ${url}`);
    try {
      return await retry(
        async () => {
          const resp = await fetch(url);
          if (!resp.ok) {
            const error = new BailableError(
              `download: ${resp.status} ${resp.statusText} for ${url}`
            );
            if (resp.status === 403) error.bail = true;
            throw error;
          }
          return resp.body;
        },
        { factor: 1, retries: 3 }
      );
    } finally {
      // console.timeEnd(`downloading ${url}`);
      semaToDownloadFromS3.release();
github kayteh / roleypoly / packages / roleypoly-bot / src / Bot.ts View on Github external
})

    // this.$RPC = new RPCClient({ forceDev: false, retry: true })
    // this.rpc = this.$RPC.withBotAuth(this.config.sharedSecret)
    this.botPing()

    if (this.config.sharedSecret === '') {
      log.fatal('configuration incomplete: SHARED_SECRET missing')
    }

    if (this.config.botToken === '') {
      log.fatal('configuration incomplete: DISCORD_BOT_TOKEN missing')
    }

    // <@botid> AND <@!botid> both are valid mentions.
    retry(() => { this.commandCheck = new RegExp(`^<@!?${this.client.user.id}>`) })
  }
github apollographql / apollo-server / packages / apollo-engine-reporting / src / agent.ts View on Github external
);
      gzip(messageBuffer, (err, gzipResult) => {
        if (err) {
          reject(err);
        } else {
          resolve(gzipResult);
        }
      });
    });

    const endpointUrl =
      (this.options.endpointUrl || 'https://engine-report.apollodata.com') +
      '/api/ingress/traces';

    // Wrap fetch with async-retry for automatic retrying
    const response: Response = await retry(
      // Retry on network errors and 5xx HTTP
      // responses.
      async () => {
        const curResponse = await fetch(endpointUrl, {
          method: 'POST',
          headers: {
            'user-agent': 'apollo-engine-reporting',
            'x-api-key': this.apiKey,
            'content-encoding': 'gzip',
          },
          body: compressed,
          agent: this.options.requestAgent,
        });

        if (curResponse.status >= 500 && curResponse.status < 600) {
          throw new Error(
github zeit / now / packages / now-cli / src / util / events.js View on Github external
let eventsUrl = `/v1/now/deployments/${deploymentIdOrURL}/events?${q}`;
  let pollUrl = `/v3/now/deployments/${deploymentIdOrURL}`;

  if (currentTeam) {
    eventsUrl += `&teamId=${currentTeam.id}`;
    pollUrl += `?teamId=${currentTeam.id}`;
  }

  debug(`Events ${eventsUrl}`);

  // we keep track of how much we log in case we
  // drop the connection and have to start over
  let o = 0;

  await retry(
    async (bail, attemptNumber) => {
      if (attemptNumber > 1) {
        debug('Retrying events');
      }

      const eventsRes = await now._fetch(eventsUrl);

      if (eventsRes.ok) {
        const readable = eventsRes.readable
          ? await eventsRes.readable()
          : eventsRes.body;

        // handle the event stream and make the promise get rejected
        // if errors occur so we can retry
        return new Promise((resolve, reject) => {
          const stream = readable.pipe(jsonlines.parse());
github happo / happo.io / src / compareSnapshots.js View on Github external
async function fetchPngWithRetry(url) {
  const bitmap = await asyncRetry(() => fetchPng(url), {
    retries: 3,
    onRetry: (e) => {
      console.warn(`Retrying fetch for ${url}. Error was: ${e.message}`);
    },
  });
  return bitmap;
}
github zeit / next.js / packages / next / telemetry / post-payload.ts View on Github external
export function _postPayload(endpoint: string, body: object) {
  return (
    retry(
      () =>
        fetch(endpoint, {
          method: 'POST',
          body: JSON.stringify(body),
          headers: { 'content-type': 'application/json' },
          timeout: 5000,
        }).then(res => {
          if (!res.ok) {
            const err = new Error(res.statusText)
            ;(err as any).response = res
            throw err
          }
        }),
      { minTimeout: 500, retries: 1, factor: 1 }
    )
      .catch(() => {
github zeit / now / packages / now-cli / src / util / index.js View on Github external
retry(fn, { retries = 3, maxTimeout = Infinity } = {}) {
    return retry(fn, {
      retries,
      maxTimeout,
      onRetry: this._onRetry,
    });
  }
github zeit / now / packages / now-cli / src / util / index.js View on Github external
retry(fn, { retries = 3, maxTimeout = Infinity } = {}) {
    return retry(fn, {
      retries,
      maxTimeout,
      onRetry: this._onRetry
    });
  }
github zeit / now / packages / now-cli / src / util / domains / add-domain.ts View on Github external
async function performAddRequest(
  client: Client,
  domainName: string
) {
  return retry(
    async () => {
      try {
        const { domain } = await client.fetch('/v4/domains', {
          body: { name: domainName },
          method: 'POST'
        });
        return domain;
      } catch (error) {
        if (error.code === 'invalid_name') {
          return new InvalidDomain(domainName);
        }

        if (error.code === 'domain_already_exists') {
          return new DomainAlreadyExists(domainName);
        }

async-retry

Retrying made simple, easy and async

MIT
Latest version published 3 years ago

Package Health Score

74 / 100
Full package analysis

Popular async-retry functions

Similar packages