AsyncParallelBailHook.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Hook = require("./Hook");
  7. const HookCodeFactory = require("./HookCodeFactory");
  8. class AsyncParallelBailHookCodeFactory extends HookCodeFactory {
  9. content({ onError, onResult, onDone }) {
  10. let code = "";
  11. code += `var _results = new Array(${this.options.taps.length});\n`;
  12. code += "var _checkDone = () => {\n";
  13. code += "for(var i = 0; i < _results.length; i++) {\n";
  14. code += "var item = _results[i];\n";
  15. code += "if(item === undefined) return false;\n";
  16. code += "if(item.result !== undefined) {\n";
  17. code += onResult("item.result");
  18. code += "return true;\n";
  19. code += "}\n";
  20. code += "if(item.error) {\n";
  21. code += onError("item.error");
  22. code += "return true;\n";
  23. code += "}\n";
  24. code += "}\n";
  25. code += "return false;\n";
  26. code += "}\n";
  27. code += this.callTapsParallel({
  28. onError: (i, err, done, doneBreak) => {
  29. let code = "";
  30. code += `if(${i} < _results.length && ((_results.length = ${i + 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`;
  31. code += doneBreak(true);
  32. code += "} else {\n";
  33. code += done();
  34. code += "}\n";
  35. return code;
  36. },
  37. onResult: (i, result, done, doneBreak) => {
  38. let code = "";
  39. code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i + 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`;
  40. code += doneBreak(true);
  41. code += "} else {\n";
  42. code += done();
  43. code += "}\n";
  44. return code;
  45. },
  46. onTap: (i, run, done, doneBreak) => {
  47. let code = "";
  48. if(i > 0) {
  49. code += `if(${i} >= _results.length) {\n`;
  50. code += done();
  51. code += "} else {\n";
  52. }
  53. code += run();
  54. if(i > 0) code += "}\n";
  55. return code;
  56. },
  57. onDone
  58. });
  59. return code;
  60. }
  61. }
  62. const factory = new AsyncParallelBailHookCodeFactory();
  63. class AsyncParallelBailHook extends Hook {
  64. constructor(args) {
  65. super(args);
  66. this.call = this._call = undefined;
  67. }
  68. compile(options) {
  69. factory.setup(this, options);
  70. return factory.create(options);
  71. }
  72. }
  73. module.exports = AsyncParallelBailHook;