Skip to content

Instantly share code, notes, and snippets.

@xiekw2010
Last active January 12, 2017 05:44
Show Gist options
  • Save xiekw2010/6166d328ccea8603de63f88f31481c3b to your computer and use it in GitHub Desktop.
Save xiekw2010/6166d328ccea8603de63f88f31481c3b to your computer and use it in GitHub Desktop.
sliceTasks
'use strict'
const _ = require('lodash')
const LOGGER_PREFIX = '[CHUNK_TASK_MANAGER]***'
function sleep(s) {
return new Promise(resolve => setTimeout(resolve, s * 1000))
}
/**
*
* @param tasks the promise array
* @param slice how to slice the tasks
* @param interval how long to do the task
*/
module.exports = function* (tasks, slice, interval) {
slice = slice || 10
interval = interval || 1
const chunks = _.chunk(tasks, slice)
let chunk = chunks.shift(), res = []
while (chunk) {
res.push(yield chunk.map(fn => {
if (typeof fn === 'function') return fn()
return fn
}))
console.log(`${LOGGER_PREFIX} sleeping... ${interval} secs`)
yield sleep(interval)
chunk = chunks.shift()
}
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment