AsyncParallelBailHook.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 = function() {\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. const COMPILE = function(options) {
  66. factory.setup(this, options);
  67. return factory.create(options);
  68. };
  69. function AsyncParallelBailHook(args = [], name = undefined) {
  70. const hook = new Hook(args, name);
  71. hook.constructor = AsyncParallelBailHook;
  72. hook.compile = COMPILE;
  73. hook._call = undefined;
  74. hook.call = undefined;
  75. return hook;
  76. }
  77. AsyncParallelBailHook.prototype = null;
  78. module.exports = AsyncParallelBailHook;