mirror of
https://github.com/gnh1201/welsonjs.git
synced 2024-11-26 15:31:42 +00:00
Create task.js
This commit is contained in:
parent
59cfb65494
commit
298a5d15d2
108
lib/task.js
Normal file
108
lib/task.js
Normal file
|
@ -0,0 +1,108 @@
|
|||
//////////////////////////////////////////////////////////////////////////////////
|
||||
// Task API (Async implementation in WSH)
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
var Task = function(id, f, params) {
|
||||
this.id = id;
|
||||
this.f = f;
|
||||
this.params = params;
|
||||
this.nextTask = null;
|
||||
this.setNextTask = function(task) {
|
||||
this.nextTask = task;
|
||||
}
|
||||
};
|
||||
|
||||
var TaskQueue = function() {
|
||||
this._task = null;
|
||||
this.queue = [];
|
||||
this.put = function(task) {
|
||||
try {
|
||||
this._task = task;
|
||||
this.queue.push(this._task);
|
||||
this.lastId++;
|
||||
} catch(e) {
|
||||
console.error("TaskQueue.put exception: " + e.message);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
this.get = function() {
|
||||
var task = null;
|
||||
|
||||
try {
|
||||
if (this.queue.length > 0) {
|
||||
task = this.queue[0];
|
||||
this.queue = this.queue.slice(1);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error("TaskQueue.get: " + e.message);
|
||||
}
|
||||
|
||||
return task;
|
||||
};
|
||||
this.next = function() {
|
||||
var result = null;
|
||||
|
||||
try {
|
||||
var task = this.get();
|
||||
|
||||
if (task != null) {
|
||||
try {
|
||||
result = task.f.apply(null, task.params);
|
||||
} catch (e) {
|
||||
console.error("Task exception: " + e.message);
|
||||
}
|
||||
|
||||
if (task.nextTask != null) {
|
||||
this.put(task.nextTask);
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
console.error("TaskQueue.next: " + e.message);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
this.then = function(task) {
|
||||
try {
|
||||
this._task.setNextTask(task);
|
||||
this._task = task;
|
||||
return this;
|
||||
} catch(e) {
|
||||
console.error("TaskQueue.then: " + e.message);
|
||||
}
|
||||
};
|
||||
this.lastId = 0;
|
||||
};
|
||||
|
||||
exports.createQueue = function() {
|
||||
return new TaskQueue();
|
||||
};
|
||||
|
||||
exports.makeTask = function(q, f, params) {
|
||||
try {
|
||||
if (q instanceof TaskQueue) {
|
||||
return new Task(q.lastId, f, params);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error("makeTask exception: " + e.message);
|
||||
}
|
||||
};
|
||||
|
||||
exports.putTask = function(q, f, params) {
|
||||
try {
|
||||
if (q instanceof TaskQueue) {
|
||||
return q.put(new Task(q.lastId, f, params));
|
||||
}
|
||||
} catch(e) {
|
||||
console.error("putTask exception: " + e.message);
|
||||
}
|
||||
};
|
||||
|
||||
exports.nextTask = function(q) {
|
||||
try {
|
||||
return q.next();
|
||||
} catch(e) {
|
||||
console.error("nextTask exception: " + e.message);
|
||||
}
|
||||
};
|
Loading…
Reference in New Issue
Block a user