Created
September 8, 2017 11:12
-
-
Save hefangshi/b1ab29904dfbfa60a90981d4c97079f9 to your computer and use it in GitHub Desktop.
Job
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created Date: Friday, September 8th 2017, 6:50:56 pm | |
* Author: hefangshi | |
* Copyright (c) 2017 Baidu.Inc | |
* | |
*/ | |
class Job { | |
constructor() { | |
this.running = 0; | |
this.finish = 0; | |
this.failed = 0; | |
this.jobs = []; | |
this.onUpdateEventHandler = null; | |
} | |
addJob(job) { | |
this.jobs.push(job); | |
} | |
onUpdate(callback) { | |
this.onUpdateEventHandler = callback; | |
} | |
run() { | |
return Promise.all(this.jobs.map(job => { | |
this.running++; | |
return job().then(ret => { | |
if (ret === false) { | |
throw new Error(`job failed`); | |
} | |
this.finish++ | |
this.running--; | |
this.onUpdateEventHandler && this.onUpdateEventHandler(); | |
return ret; | |
}).catch(() => { | |
this.failed++; | |
this.running--; | |
this.onUpdateEventHandler && this.onUpdateEventHandler(); | |
return false; | |
}); | |
})); | |
} | |
} | |
const EagleJob = function (context) { | |
return async function () { | |
if (!context.isAgile) { | |
return true; | |
} | |
return await callEagle() | |
} | |
} | |
const CIJob = function (context) { | |
return async function () { | |
return await callCI() | |
} | |
} | |
const NotImportantJob = function (context) { | |
return async function () { | |
try { | |
return await callSthNotImportant(); | |
} catch (e) { | |
return false; | |
} | |
} | |
} | |
const context = {}; | |
const reviewJobs = new Job(); | |
setState = console.log.bind(console); | |
reviewJobs.addJob(EagleJob(context)); | |
reviewJobs.addJob(CIJob(context)); | |
reviewJobs.addJob(NotImportantJob(context)); | |
reviewJobs.onUpdate(() => { | |
setState('running', reviewJobs.running); | |
setState('failed', reviewJobs.failed); | |
setState('finish', reviewJobs.finish); | |
}) | |
reviewJobs.run().then(console.log).catch(console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment