From 8ea9da78ff06902b8e2193dcf97d511191073df6 Mon Sep 17 00:00:00 2001 From: Jmeas Date: Thu, 7 Dec 2017 01:18:19 -0800 Subject: [PATCH] Support abort API --- fetch.js | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/fetch.js b/fetch.js index f2f466d7..4d6484a5 100644 --- a/fetch.js +++ b/fetch.js @@ -1,7 +1,21 @@ (function(self) { 'use strict'; - if (self.fetch) { + function canAbortFetch() { + if (!self.AbortController || !self.AbortSignal) { + return false + } + + var abortController = new self.AbortController() + + var request = new self.Request('http://a', { + signal: abortController.signal + }) + + return Boolean(request.signal) + } + + if (self.fetch && canAbortFetch()) { return } @@ -443,6 +457,10 @@ reject(new TypeError('Network request failed')) } + xhr.onabort = function() { + reject(new DOMException('Aborted', 'AbortError')) + } + xhr.open(request.method, request.url, true) if (request.credentials === 'include') { @@ -459,6 +477,10 @@ xhr.setRequestHeader(name, value) }) + if (init.signal && init.signal.addEventListener) { + init.signal.addEventListener('abort', xhr.cancel) + } + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) }) }