Kevin Kwok
8 years ago
committed by
GitHub
4 changed files with 109 additions and 82 deletions
@ -0,0 +1,81 @@
@@ -0,0 +1,81 @@
|
||||
const adapter = require('../node/index.js') |
||||
|
||||
let jobCounter = 0; |
||||
|
||||
module.exports = class TesseractJob { |
||||
constructor(instance){ |
||||
this.id = 'Job-' + (++jobCounter) + '-' + Math.random().toString(16).slice(3, 8) |
||||
|
||||
this._instance = instance; |
||||
this._resolve = [] |
||||
this._reject = [] |
||||
this._progress = [] |
||||
this._finally = [] |
||||
} |
||||
|
||||
then(resolve, reject){ |
||||
if(this._resolve.push){ |
||||
this._resolve.push(resolve) |
||||
}else{ |
||||
resolve(this._resolve) |
||||
} |
||||
|
||||
if(reject) this.catch(reject); |
||||
return this; |
||||
} |
||||
catch(reject){ |
||||
if(this._reject.push){ |
||||
this._reject.push(reject) |
||||
}else{ |
||||
reject(this._reject) |
||||
} |
||||
return this; |
||||
} |
||||
progress(fn){ |
||||
this._progress.push(fn) |
||||
return this; |
||||
} |
||||
finally(fn) { |
||||
this._finally.push(fn) |
||||
return this; |
||||
} |
||||
_send(action, payload){ |
||||
adapter.sendPacket(this._instance, { |
||||
jobId: this.id, |
||||
action: action, |
||||
payload: payload |
||||
}) |
||||
} |
||||
|
||||
_handle(packet){ |
||||
var data = packet.data; |
||||
let runFinallyCbs = false; |
||||
|
||||
if(packet.status === 'resolve'){ |
||||
if(this._resolve.length === 0) console.debug(data); |
||||
this._resolve.forEach(fn => { |
||||
var ret = fn(data); |
||||
if(ret && typeof ret.then == 'function'){ |
||||
console.warn('TesseractJob instances do not chain like ES6 Promises. To convert it into a real promise, use Promise.resolve.') |
||||
} |
||||
}) |
||||
this._resolve = data; |
||||
this._instance._dequeue() |
||||
runFinallyCbs = true; |
||||
}else if(packet.status === 'reject'){ |
||||
if(this._reject.length === 0) console.error(data); |
||||
this._reject.forEach(fn => fn(data)) |
||||
this._reject = data; |
||||
this._instance._dequeue() |
||||
runFinallyCbs = true; |
||||
}else if(packet.status === 'progress'){ |
||||
this._progress.forEach(fn => fn(data)) |
||||
}else{ |
||||
console.warn('Message type unknown', packet.status) |
||||
} |
||||
|
||||
if (runFinallyCbs) { |
||||
this._finally.forEach(fn => fn(data)); |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue