-
Notifications
You must be signed in to change notification settings - Fork 0
/
alfred-schedule.js
44 lines (37 loc) · 957 Bytes
/
alfred-schedule.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const PersistentFunctionQueue = require('./persistent-function-queue')
const alfy = require('alfy')
const io = require('./alfred-io')
const db = require('./env-db')
const log = require('./log')
const fq = new PersistentFunctionQueue(db)
function step (func) {
fq.enqueue(func)
return {
next: step
}
}
function tick () {
let input = alfy.input
try {
if (input !== undefined) input = JSON.parse(input)
} catch (e) {
// console.log(`Got error ${e} when parsing JSON.`)
// console.log('No biggy. Continuing.')
}
const result = fq.dequeue(input)
Promise.resolve(result).then(output => io.output(output, db.serialize()))
}
function first (func) {
// run on the next tick of the event loop
setTimeout(tick, 0)
return step(func)
}
function schedule (scheduler) {
if (fq.isEmpty()) {
log.debug('function queue was empty when scheduling')
scheduler(first)
} else {
tick()
}
}
module.exports = schedule