How to use the p-retry function in p-retry

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 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 => {
github StoDevX / AAO-React-Native / source / views / menus / menu-bonapp.js View on Github external
fetchData = async (props: Props) => {
		let cafeMenu: ?MenuInfoType = null
		let cafeInfo: ?CafeInfoType = null

		try {
			;[cafeMenu, cafeInfo] = await Promise.all([
				retry(this.requestMenu(props.cafeId), {retries: 3}),
				retry(this.requestCafe(props.cafeId), {retries: 3}),
			])
		} catch (error) {
			if (error.message === "JSON Parse error: Unrecognized token '<'") {
				this.setState(() => ({errormsg: BONAPP_HTML_ERROR_CODE}))
			} else {
				tracker.trackException(error.message)
				bugsnag.notify(error)
				this.setState(() => ({errormsg: error.message}))
			}
		}

		this.setState(() => ({cafeMenu, cafeInfo, now: moment.tz(CENTRAL_TZ)}))
	}
github sourcegraph / sourcegraph / lsif / src / shared / store / uploads.ts View on Github external
throw new UploadInProgressError()
            }
        }

        const retryConfig =
            maxWait === undefined
                ? { forever: true }
                : {
                      factor: 1,
                      retries: maxWait,
                      minTimeout: 1000,
                      maxTimeout: 1000,
                  }

        try {
            await pRetry(checkUploadState, retryConfig)
        } catch (error) {
            if (error && error.code === UPLOADINPROGRESS) {
                return false
            }

            throw error
        }

        return true
    }
github sourcegraph / sourcegraph / lsif / src / shared / database / postgres.ts View on Github external
function connect(connectionOptions: PostgresConnectionCredentialsOptions, logger: Logger): Promise {
    return pRetry(
        () => {
            logger.debug('Connecting to Postgres')
            return connectPostgres(connectionOptions, '')
        },
        {
            factor: 1,
            retries: MAX_CONNECTION_RETRIES,
            minTimeout: CONNECTION_RETRY_INTERVAL * 1000,
            maxTimeout: CONNECTION_RETRY_INTERVAL * 1000,
        }
    )
}
github StoDevX / AAO-React-Native / source / views / menus / menu-bonapp.js View on Github external
fetchData = async (props: Props) => {
		let cafeMenu: ?MenuInfoType = null
		let cafeInfo: ?CafeInfoType = null

		try {
			;[cafeMenu, cafeInfo] = await Promise.all([
				retry(this.requestMenu(props.cafeId), {retries: 3}),
				retry(this.requestCafe(props.cafeId), {retries: 3}),
			])
		} catch (error) {
			if (error.message === "JSON Parse error: Unrecognized token '<'") {
				this.setState(() => ({errormsg: BONAPP_HTML_ERROR_CODE}))
			} else {
				tracker.trackException(error.message)
				bugsnag.notify(error)
				this.setState(() => ({errormsg: error.message}))
			}
		}

		this.setState(() => ({cafeMenu, cafeInfo, now: moment.tz(CENTRAL_TZ)}))
	}

p-retry

Retry a promise-returning or async function

MIT
Latest version published 4 months ago

Package Health Score

80 / 100
Full package analysis

Popular p-retry functions