Skip to content

Commit

Permalink
errors and schedualling
Browse files Browse the repository at this point in the history
  • Loading branch information
calvinmetcalf authored and Calvin Metcalf committed Apr 22, 2015
1 parent 585db67 commit 774a338
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 4 deletions.
26 changes: 22 additions & 4 deletions browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,43 @@
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}

function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var currentQueue;

var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
while (++queueIndex < len) {
currentQueue[queueIndex]();
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}

process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"keywords": [
"process"
],
"scripts": {
"test": "mocha test.js"
},
"version": "0.10.1",
"repository": {
"type": "git",
Expand All @@ -14,5 +17,8 @@
"main": "./index.js",
"engines": {
"node": ">= 0.6.0"
},
"devDependencies": {
"mocha": "2.2.1"
}
}
29 changes: 29 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var ourProcess = require('./browser');
var assert = require('assert');

describe('test errors', function (t) {
it ('works', function (done) {
var order = 0;
process.removeAllListeners('uncaughtException');
process.once('uncaughtException', function(err) {
assert.equal(2, order++, 'error is third');
process.nextTick(function () {
assert.equal(5, order++, 'schedualed in error is last');
done();
});
});
process.nextTick(function () {
assert.equal(0, order++, 'first one works');
process.nextTick(function () {
assert.equal(4, order++, 'recursive one is 4th');
});
});
process.nextTick(function () {
assert.equal(1, order++, 'second one starts');
throw(new Error('an error is thrown'));
});
process.nextTick(function () {
assert.equal(3, order++, '3rd schedualed happens after the error');
});
});
});

0 comments on commit 774a338

Please sign in to comment.