feat(cron): wait promise before next run (#47)

This commit is contained in:
Julien Fontanet 2018-02-06 17:29:28 +01:00 committed by GitHub
parent 247e797d2b
commit adaa7ca413
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 7 deletions

View File

@ -29,6 +29,9 @@ job.start()
job.stop() job.stop()
``` ```
> If the scheduled job returns a promise, its resolution (or
> rejection) will be awaited before scheduling the next run.
### Pattern syntax ### Pattern syntax
``` ```

View File

@ -7,22 +7,29 @@ const MAX_DELAY = 2 ** 31 - 1
class Job { class Job {
constructor (schedule, fn) { constructor (schedule, fn) {
const wrapper = scheduledRun => { const wrapper = () => {
if (scheduledRun) { const result = fn()
fn() let then
if (result != null && typeof (then = result.then) === 'function') {
then.call(result, scheduleNext, scheduleNext)
} else {
scheduleNext()
} }
}
const scheduleNext = () => {
const delay = schedule._nextDelay() const delay = schedule._nextDelay()
this._timeout = delay < MAX_DELAY this._timeout = delay < MAX_DELAY
? setTimeout(wrapper, delay, true) ? setTimeout(wrapper, delay)
: setTimeout(wrapper, MAX_DELAY) : setTimeout(scheduleNext, MAX_DELAY)
} }
this._fn = wrapper
this._scheduleNext = scheduleNext
this._timeout = undefined this._timeout = undefined
} }
start () { start () {
this.stop() this.stop()
this._fn() this._scheduleNext()
} }
stop () { stop () {