diff --git a/index.js b/index.js index da1d9db..a1deb4d 100644 --- a/index.js +++ b/index.js @@ -51,11 +51,18 @@ function createXHR(uri, options, callback) { } function _createXHR(options) { - var callback = options.callback - if(typeof callback === "undefined"){ + if(typeof options.callback === "undefined"){ throw new Error("callback argument missing") } + var called = false + var callback = function cbOnce(err, response, body){ + if(!called){ + called = true + options.callback(err, response, body) + } + } + function readystatechange() { if (xhr.readyState === 4) { loadFunc() @@ -96,8 +103,7 @@ function _createXHR(options) { evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) } evt.statusCode = 0 - callback(evt, failureResponse) - callback = noop + return callback(evt, failureResponse) } // will load the data & process the response in a special response object @@ -129,9 +135,7 @@ function _createXHR(options) { } else { err = new Error("Internal XMLHttpRequest Error") } - callback(err, response, response.body) - callback = noop - + return callback(err, response, response.body) } var xhr = options.xhr || null diff --git a/test/index.js b/test/index.js index 541cd3f..651ea94 100644 --- a/test/index.js +++ b/test/index.js @@ -52,6 +52,22 @@ test("[func] Returns a falsy body for 204 responses", function(assert) { }) }) +test("[func] Calls the callback once even if error is thrown issue #127", function(assert) { + var count = 0; + setTimeout(function(){ + assert.equal(count, 1, "expected one call") + assert.end() + },100) + try{ + xhr({ + uri: "instanterror://foo" + }, function(err, resp, body) { + count++; + throw Error("dummy error") + }) + } catch(e){} +}) + test("[func] Times out to an error ", function(assert) { xhr({ timeout: 1,