From cda7b71146f6748116ad5bbc9050ee7e79a9ce2b Mon Sep 17 00:00:00 2001 From: David Bennett Date: Wed, 24 Apr 2013 12:33:08 -0500 Subject: feat($httpBackend): add timeout support for JSONP requests Documentation implies that timeout works for all requests, though it only works with XHR. To implement: - Change $httpBackend to set a timeout for JSONP requests which will immediately resolve the request when fired. - Cancel the timeout when requests are completed. --- src/ng/httpBackend.js | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/ng/httpBackend.js b/src/ng/httpBackend.js index a3f6cdc0..69ac5976 100644 --- a/src/ng/httpBackend.js +++ b/src/ng/httpBackend.js @@ -33,6 +33,7 @@ function $HttpBackendProvider() { function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { + var status; $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); @@ -42,12 +43,12 @@ function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, callbacks[callbackId].data = data; }; - jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), + var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { - completeRequest(callback, -2); + completeRequest(callback, status || -2); } delete callbacks[callbackId]; }); @@ -58,8 +59,6 @@ function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, if (value) xhr.setRequestHeader(key, value); }); - var status; - // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async @@ -105,13 +104,14 @@ function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, } xhr.send(post || ''); + } - if (timeout > 0) { - $browserDefer(function() { - status = -1; - xhr.abort(); - }, timeout); - } + if (timeout > 0) { + var timeoutId = $browserDefer(function() { + status = -1; + jsonpDone && jsonpDone(); + xhr && xhr.abort(); + }, timeout); } @@ -119,6 +119,9 @@ function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, // URL_MATCH is defined in src/service/location.js var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1]; + // cancel timeout + timeoutId && $browserDefer.cancel(timeoutId); + // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; @@ -152,5 +155,6 @@ function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, } rawDocument.body.appendChild(script); + return doneWrapper; } } -- cgit v1.2.3