Last active
January 12, 2017 05:44
-
-
Save xiekw2010/6166d328ccea8603de63f88f31481c3b to your computer and use it in GitHub Desktop.
sliceTasks
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
'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