Skip to content

Commit

Permalink
fix #127 ensure callback called once even if it throws
Browse files Browse the repository at this point in the history
  • Loading branch information
naugtur committed Jul 22, 2016
1 parent 40c5564 commit 67958b7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
18 changes: 11 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 67958b7

Please sign in to comment.