You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.2 KiB

4 years ago
  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 +
  31. 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`;
  32. code += doneBreak(true);
  33. code += "} else {\n";
  34. code += done();
  35. code += "}\n";
  36. return code;
  37. },
  38. onResult: (i, result, done, doneBreak) => {
  39. let code = "";
  40. code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i +
  41. 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`;
  42. code += doneBreak(true);
  43. code += "} else {\n";
  44. code += done();
  45. code += "}\n";
  46. return code;
  47. },
  48. onTap: (i, run, done, doneBreak) => {
  49. let code = "";
  50. if (i > 0) {
  51. code += `if(${i} >= _results.length) {\n`;
  52. code += done();
  53. code += "} else {\n";
  54. }
  55. code += run();
  56. if (i > 0) code += "}\n";
  57. return code;
  58. },
  59. onDone
  60. });
  61. return code;
  62. }
  63. }
  64. const factory = new AsyncParallelBailHookCodeFactory();
  65. class AsyncParallelBailHook extends Hook {
  66. compile(options) {
  67. factory.setup(this, options);
  68. return factory.create(options);
  69. }
  70. }
  71. Object.defineProperties(AsyncParallelBailHook.prototype, {
  72. _call: { value: undefined, configurable: true, writable: true }
  73. });
  74. module.exports = AsyncParallelBailHook;