[Javascript] AbortController to cancel the fetch request

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] AbortController to cancel the fetch request相关的知识,希望对你有一定的参考价值。

We are able to cancel the fetch request by using AbortController with RxJS Observable.

return Observable.create(observer => {
  // Create an AbortController to able to cancel the fetch request
  const controller = new AbortController();
  // we need singal to pass to the fetch request
  const signal = controller.singal;
  // Pass the singal in fetch options
  fetch(url, { singal })
    .then(response => {
      return response.json();
    })
    .then(body => {
      observer.next(body);
      observer.complete();
    })
    .catch(err => {
      observer.error(err);
    });
  // When comsumer call sub.unsubscribe(), it will call abort()
  // to cancel the request.
  return () => controller.abort();
});

 

以上是关于[Javascript] AbortController to cancel the fetch request的主要内容,如果未能解决你的问题,请参考以下文章

javascript JavaScript isset()等效: - JavaScript

JavaScript 使用JavaScript更改CSS(JavaScript)

JavaScript之基础-1 JavaScript(概述基础语法)

前端基础-JavaScript的基本概述和语法

JavaScript

JavaScript