Skip to content

Commit

Permalink
Use process.nextTick or window.setTimeout so that tasks do not have o…
Browse files Browse the repository at this point in the history
…ther tasks in their call stack
  • Loading branch information
philidem committed Nov 3, 2015
1 parent 1db5d38 commit 410cee7
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 16 deletions.
38 changes: 22 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ var series = require('raptor-async/series');

var NOOP = function() {};
var _Promise = (typeof Promise === 'undefined') ? undefined : Promise;
var nextTick = require('./nextTick');

var TaskState = exports.TaskState = {
INITIAL: {},
Expand Down Expand Up @@ -137,21 +138,28 @@ function _isPromise(obj) {

function _invokeTask(task, funcName, callback) {
var func = task[funcName];
// Invoke task in next tick so that the previous task is not in
// the call stack of new task
if (func.length === 0) {
var result = func.call(task);
if (_isPromise(result)) {
// task function returned promise so normalize to callback
result.then(function() {
nextTick(function() {
var result = func.call(task);
if (_isPromise(result)) {
// task function returned promise so normalize to callback
result.then(function() {
callback();
}).catch(function(err) {
callback(err || new Error('Task failed to ' + funcName));
});
} else {
// function is synchronous
callback();
}).catch(function(err) {
callback(err || new Error('Task failed to ' + funcName));
});
} else {
// function is synchronous
callback();
}
}
});
} else {
func.call(task, callback);

nextTick(function() {
func.call(task, callback);
});
}
}

Expand Down Expand Up @@ -218,15 +226,13 @@ TaskList_prototype.startAll = function(callback) {
_invokeTask(task, 'start', function(startErr) {
if (startErr) {
task.state = TaskState.ERROR;

logger.error(task.type.startErrorMessage(task));

callback(startErr);
} else {
task.state = TaskState.STARTED;
logger.success(task.type.startedMessage(task));
callback();
}

callback(startErr);
});
});

Expand Down
2 changes: 2 additions & 0 deletions nextTick.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Node.js version of nextTick
module.exports = process.nextTick.bind(process);
4 changes: 4 additions & 0 deletions nextTick_browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// browser version of nextTick
module.exports = function(fn) {
setTimeout(fn, 0);
};
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
"data-modeling",
"modeling"
],
"browser": {
"./nextTick.js": "./nextTick_browser.js"
},
"homepage": "https://github.com/philidem/task-list",
"repository": {
"type": "git",
Expand Down

0 comments on commit 410cee7

Please sign in to comment.