[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();
});

 

    原文作者:Zhentiw
    原文地址: https://www.cnblogs.com/Answer1215/p/9275003.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞