You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
As we know, `fetch`returns a promise. AndJavaScript generally has no concept of "aborting" a promise. So how can we cancel an ongoing`fetch`?E.g. if the user actions on our site indicate that the `fetch`isn't needed any more.
Як ми знаємо, `fetch`повертає проміс. А вJavaScript, як правило, немає концепції "переривання" промісу. Отже, як ми можемо перервати поточний`fetch`?Наприклад, якщо дії користувача на нашому сайті вказують на те, що `fetch`більше не потрібен.
There's a special built-in object for such purposes: `AbortController`.It can be used to abort not only`fetch`,but other asynchronous tasks as well.
Для таких цілей є спеціальний вбудований об’єкт: `AbortController`.Його можна використовувати для переривання не тільки`fetch`,але й інших асинхронних завдань.
The usage is very straightforward:
Його використання дуже просте:
##The AbortController object
##Об’єкт AbortController
Create a controller:
Створімо контролер:
```js
let controller = new AbortController();
```
A controller is an extremely simple object.
Контролер -- це надзвичайно простий об’єкт.
-It has a single method `abort()`,
-And a single property`signal` that allows to set event listeners on it.
-Він має єдиний метод `abort()`,
-І єдину властивість`signal`, що дозволяє встановлювати на ньому обробники подій.
let fetchJobs = urls.map(url => fetch(url, { //fetches
let fetchJobs = urls.map(url => fetch(url, { //запити fetch
signal: controller.signal
}));
//Wait for fetches and our task in parallel
//Чекаємо на виконання запитів fetch та наших завдань паралельно
let results = await Promise.all([...fetchJobs, ourJob]);
//if controller.abort()is called from anywhere,
//it aborts all fetches and ourJob
//якщо controller.abort()викликається з будь-якого місця,
//він перериває всі fetch та ourJob
```
##Summary
##Підсумки
- `AbortController`is a simple object that generates an `abort`event on it's `signal`property when the`abort()`method is called (and also sets`signal.aborted`to `true`).
- `fetch`integrates with it: we pass the `signal`property as the option, and then `fetch`listens to it, so it's possible to abort the `fetch`.
-We can use `AbortController`in our code. The "call `abort()`" -> "listen to `abort` event" interaction is simple and universal. We can use it even without `fetch`.
- `AbortController`-- це простий об’єкт, який генерує подію `abort`для своєї властивості `signal`під час виклику методу`abort()`(а також встановлює для`signal.aborted`значення `true`).
- `fetch`інтегрується з ним: ми передаємо властивість `signal`як параметр, а потім `fetch`прослуховує його, тому можна перервати цей `fetch`.
-Ми можемо використовувати `AbortController`у нашому коді. Взаємодія "виклик `abort()`" -> "прослуховування події `abort`" проста та універсальна. Ми можемо використовувати його навіть без `fetch`.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.