diff --git a/lib/helpers.js b/lib/helpers.js index 699d795cd..fa5712ffb 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -4,6 +4,13 @@ var extend = require('util')._extend , jsonSafeStringify = require('json-stringify-safe') , crypto = require('crypto') +function deferMethod() { + if(typeof setImmediate === 'undefined') { + return process.nextTick + } + + return setImmediate +} function constructObject(initialObject) { initialObject = initialObject || {} @@ -79,3 +86,4 @@ exports.safeStringify = safeStringify exports.md5 = md5 exports.isReadStream = isReadStream exports.toBase64 = toBase64 +exports.defer = deferMethod() diff --git a/request.js b/request.js index 04dcadb21..647f54660 100644 --- a/request.js +++ b/request.js @@ -14,6 +14,7 @@ var optional = require('./lib/optional') , md5 = helpers.md5 , isReadStream = helpers.isReadStream , toBase64 = helpers.toBase64 + , defer = helpers.defer , bl = require('bl') , oauth = optional('oauth-sign') , hawk = optional('hawk') @@ -654,7 +655,7 @@ Request.prototype.init = function (options) { // }) }) - process.nextTick(function () { + defer(function () { if (self._aborted) { return } @@ -761,13 +762,7 @@ Request.prototype.init = function (options) { } function wait_for_socket_response(){ - var detach - if(typeof setImmediate === 'undefined') { - detach = process.nextTick - } else { - detach = setImmediate - } - detach(function(){ + defer(function(){ // counter to prevent infinite blocking waiting for an open socket to be found. response_counter++ var trying = false