Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'async-retry' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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);
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();
})
// 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}>`) })
}
);
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(
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());
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;
}
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(() => {
retry(fn, { retries = 3, maxTimeout = Infinity } = {}) {
return retry(fn, {
retries,
maxTimeout,
onRetry: this._onRetry,
});
}
retry(fn, { retries = 3, maxTimeout = Infinity } = {}) {
return retry(fn, {
retries,
maxTimeout,
onRetry: this._onRetry
});
}
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);
}