How to use p-retry - 10 common examples

To help you get started, we’ve selected a few p-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 open-voip-alliance / WebphoneLib / src / transport.ts View on Github external
log.debug('Trying to reconnect asap.', this.constructor.name);
    // In the case that mode is BURST, a new socket is created roughly every
    // 500 ms to be able to quickly revive our connection once that succeeds.
    const retryOptions = {
      forever: true,
      maxTimeout: 100, // Note: this is time between retries, not time before operation times out
      minTimeout: 100,
      onFailedAttempt: error => {
        log.debug(
          `Connection attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`,
          this.constructor.name
        );
      }
    };

    const retryForever = pRetry(() => {
      // It could happen that this function timed out. Because this is a
      // async function we check the client status to stop this loop.
      if (this.status === ClientStatus.DISCONNECTED) {
        throw new pRetry.AbortError("It's no use. Stop trying to recover");
      }

      return tryOpeningSocketWithTimeout();
    }, retryOptions);

    console.log(`dying counter: ${this.dyingCounter}`);
    return pTimeout(retryForever, this.dyingCounter, () => {
      log.info(
        'We could not recover the session(s) within 1 minute. ' +
          'After this time the SIP server has terminated the session(s).',
        this.constructor.name
      );
github amtrack / sfdx-browserforce-plugin / src / plugins / security / identity-provider / index.ts View on Github external
public async apply(plan) {
    if (plan.enabled && plan.certificate && plan.certificate !== '') {
      // wait for cert to become available in Identity Provider UI
      await pRetry(
        async () => {
          const certsResponse = await this.org
            .getConnection()
            .tooling.query(
              `SELECT Id, DeveloperName FROM Certificate WHERE DeveloperName = '${
                plan.certificate
              }'`
            );
          if (!certsResponse.records.length) {
            throw new Error(`Could not find Certificate '${plan.certificate}'`);
          }
          const page = await this.browserforce.openPage(PATHS.EDIT_VIEW);
          await page.waitFor(SELECTORS.EDIT_BUTTON);
          await Promise.all([
            page.waitForNavigation(),
            page.click(SELECTORS.EDIT_BUTTON)
github slackapi / node-slack-sdk / src / WebClient.ts View on Github external
// Slack's Web API doesn't use meaningful status codes besides 429 and 200
        if (response.status !== 200) {
          throw httpErrorFromResponse(response);
        }

        return response;
      } catch (error) {
        this.logger.warn('http request failed', error.message);
        if (error.request) {
          throw requestErrorWithOriginal(error);
        }
        throw error;
      }
    });

    return pRetry(task, this.retryConfig);
  }
github kellyselden / create-react-app-updater / src / get-package-versions.js View on Github external
await pRetry(async() => {
      let results;

      try {
        results = await npm(`view ${parentPackageName}@${_parentVersion} dependencies --json`);
      } catch (err) {
        // occurs sometimes when running multiple npm calls at once
        if (typeof err !== 'string' || !err.includes('npm update check failed')) {
          throw new pRetry.AbortError(err);
        }

        // https://github.com/sindresorhus/p-retry/issues/14
        // throw err;
        throw new Error(err);
      }

      if (parentVersion) {
        return;
      }

      // some versions may be missing deps
      if (!results) {
        return;
      }
github webiny / webiny-js / components / serverless-aws-api-gateway / utils.js View on Github external
async () => {
            try {
                return await fn();
            } catch (error) {
                if (error.code !== "TooManyRequestsException") {
                    // Stop retrying and throw the error
                    throw new pRetry.AbortError(error);
                }
                throw error;
            }
        },
        {
github open-voip-alliance / WebphoneLib / src / transport.ts View on Github external
const retryForever = pRetry(() => {
      // It could happen that this function timed out. Because this is a
      // async function we check the client status to stop this loop.
      if (this.status === ClientStatus.DISCONNECTED) {
        throw new pRetry.AbortError("It's no use. Stop trying to recover");
      }

      return tryOpeningSocketWithTimeout();
    }, retryOptions);
github kellyselden / create-react-app-updater / src / get-package-version.js View on Github external
}).catch(err => {
            // occurs sometimes when running multiple npm calls at once
            if (typeof err !== 'string' || !err.includes('npm update check failed')) {
              throw new pRetry.AbortError(err);
            }

            // https://github.com/sindresorhus/p-retry/issues/14
            // throw err;
            throw new Error(err);
          });
        }, { retries: 5 });
github shirshak55 / scrapper-tools / src / downloader.ts View on Github external
export default async function download(filePath, url) {
  if (await exists(filePath)) {
    return
  }

  console.log(chalk.dim(`    Downloading: ${chalk.italic(url)}`))

  await pRetry(
    () => {
      new Promise((resolve, reject) => {
        got
          .stream(url, { retry: 4, throwHttpErrors: false })
          .on('error', (err) => {
            console.error(err)
            resolve()
          })
          .pipe(fs.createWriteStream(filePath))
          .on('finish', resolve)
          .on('error', (err) => {
            console.error(err)
            fs.unlink(filePath, () => resolve)
          })
      })
    },
github fanfoujs / space-fanfou / src / features / sidebar-statistics / @page.js View on Github external
async fetchUserProfileData() {
    const apiUrl = '//api.fanfou.com/users/show.json'
    const params = { id: this.getUserId() }
    const fetch = () => jsonp(apiUrl, { params })
    const userProfileData = await retry(fetch, {
      retries: 3,
      minTimeout: 250,
    })

    return userProfileData
  }
github prisma / photonjs / packages / fetch-engine / src / downloadZip.ts View on Github external
export async function downloadZip(url: string, target: string, progressCb?: (progress: number) => any) {
  const partial = target + '.partial'
  const result = await retry(
    async () => {
      try {
        const resp = await fetch(url, { compress: false, agent: getProxyAgent(url) })

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

        const lastModified = resp.headers.get('last-modified')!
        const size = parseFloat(resp.headers.get('content-length'))
        const ws = fs.createWriteStream(partial)

        return await new Promise((resolve, reject) => {
          let bytesRead = 0

          resp.body.on('error', reject).on('data', chunk => {

p-retry

Retry a promise-returning or async function

MIT
Latest version published 1 month ago

Package Health Score

85 / 100
Full package analysis

Popular p-retry functions