f27832056e0aeb1e1f1fe045812ece27db83c662.svn-base 975 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. function getType(value) {
  2. return Object.prototype.toString.call(value).slice(8, -1)
  3. }
  4. class Task {
  5. constructor({ maxParallel }) {
  6. this.maxParallel = maxParallel
  7. this.runningTotal = 0
  8. this.storage = []
  9. this.resultCb = this.resultCb.bind(this)
  10. }
  11. push(mission, cb) {
  12. this.storage.push({mission, cb})
  13. this.run()
  14. }
  15. resultCb() {
  16. this.runningTotal--
  17. this.run()
  18. }
  19. run() {
  20. if (this.storage.length === 0 ||
  21. this.maxParallel <= this.runningTotal)
  22. return;
  23. this.runningTotal++
  24. let {mission: fn, cb} = this.storage.shift()
  25. let type = getType(fn)
  26. let promise =
  27. type === 'Function' ? Promise.resolve(fn()) :
  28. type === 'Promise' ? fn :
  29. type === 'AsyncFunction' ? fn() : Promise.resolve(fn)
  30. promise.then(data => {
  31. cb && cb(data)
  32. this.resultCb()
  33. }).catch(error => {
  34. cb && cb()
  35. this.resultCb()
  36. })
  37. this.run()
  38. }
  39. }
  40. export default Task