Here's Something I Prepared Earlier (via detached child-process)
I borrowed this idea by seeing how update-notifier operates.
The ideal use case is when you have a time-consuming asynchronous task (e.g. baking a cake, making an HTTP request, scanning a disk, etc), and you'd like to continue executing, even when those results are not ready yet. You assume that during a future execution of your script, you'll have access to the results of that previous run.
type OvenOptions = {
bakePath: string,
cakeName: string,
interval?: number
}
type Cake = {
lastBaked?: number,
[id:string]: any
}
-
bakePath is a path to a module that exports a BakeFunction named "bake"
-
cakeName is a unique identifier for the background work, and scripts that use the same results can share this
-
interval is the milliseconds to wait after a successful baking, to throttle your time-consuming task (default = 1 day)
type BakeFunction = (...args: any[]) => Promise<Cake>
type BakeOptions = {
cake: Cake
}
-
your
BakeFunction
has access to the previousCake
, which could be useful for more-efficient / partial baking -
your
BakeFunction
resolves with yourCake
, and we automatically set "lastBaked" value in theCake
for you (used when checking interval)
type CakeOptions = {
cakeName: string
}
-
cakeName must be the same cake that you
putInOven()
earlier -
returns your Cake if it's ready (you'll have to check)
index.js / cli.js (your entry-point):
const path = require('path')
const Conf = require('conf')
const { getCake, putInOven } = require('hsipe')
const cakeName = 'strawberry-shortcake'
// start baking our strawberry-shortcake
putInOven({ bakePath: path.join(__dirname, 'bake.js'), cakeName })
// try to continue on, in case we already started baking last time
const cake = getCake({ cakeName })
const flavour = cake.flavour
if (flavour) {
// yay, we must have prepared something earlier
// TODO: eat cake, enjoy flavour
} else {
// ah, this must be our first time through here
// better luck next time!
// TODO: do something that doesn't require eating delicious cake
}
function bake ({ cake }, ...args) {
// e.g. something that can take a while to finish
return new Promise((resolve) => {
setTimeout(() => {
resolve({ flavour: 'delicious' })
}, 5e3)
})
}
module.exports = { bake }
npm install --global flow-typed
npm install
flow-typed install
npm test