码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] AbortController to cancel the fetch request

时间:2018-07-06 18:31:39      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:asc   server   serve   res   pre   msu   body   fetch   oms   

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

标签:asc   server   serve   res   pre   msu   body   fetch   oms   

原文地址:https://www.cnblogs.com/Answer1215/p/9275003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!