Skip to content

Commit

Permalink
use events to wire upload tracking instead of racing with setImmediate
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Stewmon authored and jstewmon committed Jul 19, 2018
1 parent 75fd8d3 commit 6eef56c
Showing 1 changed file with 11 additions and 18 deletions.
29 changes: 11 additions & 18 deletions source/request-as-event-emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,11 @@ module.exports = (options = {}) => {
return;
}

setImmediate(() => {
try {
getResponse(response, options, emitter, redirects);
} catch (error) {
emitter.emit('error', error);
}
});
try {
getResponse(response, options, emitter, redirects);
} catch (error) {
emitter.emit('error', error);
}
});

cacheReq.on('error', error => {
Expand All @@ -122,7 +120,7 @@ module.exports = (options = {}) => {

cacheReq.once('request', req => {
let aborted = false;
req.once('abort', _ => {
req.once('abort', () => {
aborted = true;
});

Expand All @@ -148,8 +146,7 @@ module.exports = (options = {}) => {
total: uploadBodySize
});

const socket = req.connection;
if (socket) {
req.once('socket', socket => {
const onSocketConnect = () => {
const uploadEventFrequency = 150;

Expand Down Expand Up @@ -183,26 +180,22 @@ module.exports = (options = {}) => {
}, uploadEventFrequency);
};

// Only subscribe to `connect` event if we're actually connecting a new
// socket, otherwise if we're already connected (because this is a
// keep-alive connection) do not bother. This is important since we won't
// get a `connect` event for an already connected socket.
if (socket.connecting) {
socket.once('connect', onSocketConnect);
} else {
// The socket is being reused from pool,
// so the connect event will not be emitted
onSocketConnect();
}
}
});
});

if (options.gotTimeout) {
clearInterval(progressInterval);
timedOut(req, options.gotTimeout);
}

setImmediate(() => {
emitter.emit('request', req);
});
emitter.emit('request', req);
});
};

Expand Down

0 comments on commit 6eef56c

Please sign in to comment.