Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'abort-controller' 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.
search,
cookie = '',
context = CONTEXT_PAGE
) {
const query = queryString.stringify({
path,
context,
...getExtraQueryParams(),
...queryString.parse(search),
...getQueryParamsFromCookies(cookie),
});
const apiUrl = `${process.env.API_ROOT_URL}/components?${query}`;
// Create abort controller and set timeout to abort fetch call.
// Default timeout is 10s, but can be configured with env var.
const controller = new AbortController();
const timeout = setTimeout(
() => controller.abort(),
env.FETCH_TIMEOUT || 10000
);
// Set up fetch options.
const options = {
headers: {
Accept: 'application/json',
},
credentials: 'include', // Support XHR with basic auth.
signal: controller.signal,
};
const response = await fetch(apiUrl, options);
// Clear timeout once response is returned (no matter what it is).
protected _fetch = async (): Promise => {
this._fetchTimeout = null;
// Don't fetch unless the cache is active.
if (!this.active) {
return;
}
this._fetchAbortController = new AbortController();
this._fetchAbortTimeout = setTimeout(() => {
if (this._fetchAbortController) {
this._fetchAbortController.abort();
}
}, (this._config.authxPublicKeyRefreshRequestTimeout || 30) * 1000);
try {
// Fetch the keys from AuthX.
// FIXME: This should not need to be cast through any. See:
// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/35636
const response = await (
await fetch(this._config.authxUrl + "/graphql", {
signal: this._fetchAbortController.signal,
method: "POST",
headers: {
"Content-Type": "application/json"
}
// Clear any refresh timeout for this token.
if (
this._refreshTimeouts[refreshToken] &&
this._refreshTimeouts[refreshToken][hash]
) {
clearTimeout(this._refreshTimeouts[refreshToken][hash]);
delete this._refreshTimeouts[refreshToken][hash];
if (!Object.keys(this._refreshTimeouts[refreshToken]).length) {
delete this._refreshTimeouts[refreshToken];
}
}
// Create a new abort controller.
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, (this._config.refreshCachedTokensRequestTimeout || 30) * 1000);
const request = {
controller,
timeout,
promise: (async () => {
try {
// FIXME: This should not need to be cast through any. See:
// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/35636
const refreshResponse = await fetch(this._config.authxUrl, {
method: "POST",
signal: controller.signal,
headers: {
"Content-Type": "application/json"
},
export async function receiveMessages(
pubsub: PubSubApi.Pubsub,
subscription: string,
metrics: GoogleMetrics,
cancel: Promise
): Promise {
// Does higher message batching lead to better throughput? 10 is the max that AWS SQS allows.
const maxMessages = 10;
const source = new AbortController();
const request = pubsub.projects.subscriptions.pull(
{
subscription,
requestBody: { returnImmediately: false, maxMessages }
},
{ signal: source.signal }
);
const response = await Promise.race([request, cancel]);
if (!response) {
source.abort();
return { Messages: [] };
}
metrics.outboundBytes += computeHttpResponseBytes(response.headers);
metrics.pubSubBytes +=
it("should throw exception if passed an already aborted signal", async function() {
const client = new CosmosClient({ endpoint, key: masterKey });
try {
const controller = new AbortController();
const signal = controller.signal;
controller.abort();
await client.getDatabaseAccount({ abortSignal: signal });
assert.fail("Must throw when trying to connect to database");
} catch (err) {
assert.equal(err.name, "AbortError", "client should throw exception");
}
});
it("should abort a query", async function() {
private _sendHit(hit: RawAnalytics): [AbortAnalytics, Promise] {
log(`Sending hit for ${hit.dp}`);
const controller = new AbortController();
const abortAnalytics = () => {
log(`Aborting hit for ${JSON.stringify(hit.dp)}`);
controller.abort();
};
const hitPayload = qs.stringify(hit);
log(`Hit payload: ${JSON.stringify(hit)}`);
const hitPromise = fetch(googleAnalyticsUrl, {
body: hitPayload,
method: "POST",
signal: controller.signal
})
export async function readFile(name: string, opts: IReadOptions): Promise {
if (isURL(name)) {
let response;
let timeout: NodeJS.Timeout | number | null = null;
try {
if (opts.timeout) {
const controller = new AbortController();
timeout = setTimeout(() => {
controller.abort();
}, opts.timeout);
response = await request(name, { signal: controller.signal });
} else {
response = await request(name);
}
if (!response.ok) throw new Error(response.statusText);
return await response.text();
} catch (ex) {
if (ex.name === 'AbortError') {
throw new Error('Timeout');
} else {
throw ex;
}
function abortAfter(ms: number) {
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, ms);
return { controller, timeout };
}
formHeaders = body.getHeaders && body.getHeaders();
} else {
const contentType = propOr(type, type, REQUEST_TYPES);
formHeaders = contentType ? { 'Content-type': contentType } : {};
if (!noBody) {
body = serialize(type, payload);
}
}
let timer;
let signal;
if (AbortController) {
const controller = new AbortController();
signal = controller.signal;
const abort = (abortOptions?) => {
if (ended) {
return;
}
ended = true;
controller.abort();
next({
status: Status.ERROR,
error: abortOptions || {},
});
};
useEffect(() => {
unstable_batchedUpdates(() => {
setIsLoading(cachedData === undefined);
setError(undefined);
setData(cachedData);
});
const abortController = new AbortController();
fetch({signal: abortController.signal});
return () => abortController.abort();
}, [fetch]);