Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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.

auto.js 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = auto;
  6. var _once = require('./internal/once');
  7. var _once2 = _interopRequireDefault(_once);
  8. var _onlyOnce = require('./internal/onlyOnce');
  9. var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
  10. var _wrapAsync = require('./internal/wrapAsync');
  11. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  12. var _promiseCallback = require('./internal/promiseCallback');
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. /**
  15. * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
  16. * their requirements. Each function can optionally depend on other functions
  17. * being completed first, and each function is run as soon as its requirements
  18. * are satisfied.
  19. *
  20. * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
  21. * will stop. Further tasks will not execute (so any other functions depending
  22. * on it will not run), and the main `callback` is immediately called with the
  23. * error.
  24. *
  25. * {@link AsyncFunction}s also receive an object containing the results of functions which
  26. * have completed so far as the first argument, if they have dependencies. If a
  27. * task function has no dependencies, it will only be passed a callback.
  28. *
  29. * @name auto
  30. * @static
  31. * @memberOf module:ControlFlow
  32. * @method
  33. * @category Control Flow
  34. * @param {Object} tasks - An object. Each of its properties is either a
  35. * function or an array of requirements, with the {@link AsyncFunction} itself the last item
  36. * in the array. The object's key of a property serves as the name of the task
  37. * defined by that property, i.e. can be used when specifying requirements for
  38. * other tasks. The function receives one or two arguments:
  39. * * a `results` object, containing the results of the previously executed
  40. * functions, only passed if the task has any dependencies,
  41. * * a `callback(err, result)` function, which must be called when finished,
  42. * passing an `error` (which can be `null`) and the result of the function's
  43. * execution.
  44. * @param {number} [concurrency=Infinity] - An optional `integer` for
  45. * determining the maximum number of tasks that can be run in parallel. By
  46. * default, as many as possible.
  47. * @param {Function} [callback] - An optional callback which is called when all
  48. * the tasks have been completed. It receives the `err` argument if any `tasks`
  49. * pass an error to their callback. Results are always returned; however, if an
  50. * error occurs, no further `tasks` will be performed, and the results object
  51. * will only contain partial results. Invoked with (err, results).
  52. * @returns {Promise} a promise, if a callback is not passed
  53. * @example
  54. *
  55. * async.auto({
  56. * // this function will just be passed a callback
  57. * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
  58. * showData: ['readData', function(results, cb) {
  59. * // results.readData is the file's contents
  60. * // ...
  61. * }]
  62. * }, callback);
  63. *
  64. * async.auto({
  65. * get_data: function(callback) {
  66. * console.log('in get_data');
  67. * // async code to get some data
  68. * callback(null, 'data', 'converted to array');
  69. * },
  70. * make_folder: function(callback) {
  71. * console.log('in make_folder');
  72. * // async code to create a directory to store a file in
  73. * // this is run at the same time as getting the data
  74. * callback(null, 'folder');
  75. * },
  76. * write_file: ['get_data', 'make_folder', function(results, callback) {
  77. * console.log('in write_file', JSON.stringify(results));
  78. * // once there is some data and the directory exists,
  79. * // write the data to a file in the directory
  80. * callback(null, 'filename');
  81. * }],
  82. * email_link: ['write_file', function(results, callback) {
  83. * console.log('in email_link', JSON.stringify(results));
  84. * // once the file is written let's email a link to it...
  85. * // results.write_file contains the filename returned by write_file.
  86. * callback(null, {'file':results.write_file, 'email':'user@example.com'});
  87. * }]
  88. * }, function(err, results) {
  89. * console.log('err = ', err);
  90. * console.log('results = ', results);
  91. * });
  92. */
  93. function auto(tasks, concurrency, callback) {
  94. if (typeof concurrency !== 'number') {
  95. // concurrency is optional, shift the args.
  96. callback = concurrency;
  97. concurrency = null;
  98. }
  99. callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)());
  100. var numTasks = Object.keys(tasks).length;
  101. if (!numTasks) {
  102. return callback(null);
  103. }
  104. if (!concurrency) {
  105. concurrency = numTasks;
  106. }
  107. var results = {};
  108. var runningTasks = 0;
  109. var canceled = false;
  110. var hasError = false;
  111. var listeners = Object.create(null);
  112. var readyTasks = [];
  113. // for cycle detection:
  114. var readyToCheck = []; // tasks that have been identified as reachable
  115. // without the possibility of returning to an ancestor task
  116. var uncheckedDependencies = {};
  117. Object.keys(tasks).forEach(key => {
  118. var task = tasks[key];
  119. if (!Array.isArray(task)) {
  120. // no dependencies
  121. enqueueTask(key, [task]);
  122. readyToCheck.push(key);
  123. return;
  124. }
  125. var dependencies = task.slice(0, task.length - 1);
  126. var remainingDependencies = dependencies.length;
  127. if (remainingDependencies === 0) {
  128. enqueueTask(key, task);
  129. readyToCheck.push(key);
  130. return;
  131. }
  132. uncheckedDependencies[key] = remainingDependencies;
  133. dependencies.forEach(dependencyName => {
  134. if (!tasks[dependencyName]) {
  135. throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', '));
  136. }
  137. addListener(dependencyName, () => {
  138. remainingDependencies--;
  139. if (remainingDependencies === 0) {
  140. enqueueTask(key, task);
  141. }
  142. });
  143. });
  144. });
  145. checkForDeadlocks();
  146. processQueue();
  147. function enqueueTask(key, task) {
  148. readyTasks.push(() => runTask(key, task));
  149. }
  150. function processQueue() {
  151. if (canceled) return;
  152. if (readyTasks.length === 0 && runningTasks === 0) {
  153. return callback(null, results);
  154. }
  155. while (readyTasks.length && runningTasks < concurrency) {
  156. var run = readyTasks.shift();
  157. run();
  158. }
  159. }
  160. function addListener(taskName, fn) {
  161. var taskListeners = listeners[taskName];
  162. if (!taskListeners) {
  163. taskListeners = listeners[taskName] = [];
  164. }
  165. taskListeners.push(fn);
  166. }
  167. function taskComplete(taskName) {
  168. var taskListeners = listeners[taskName] || [];
  169. taskListeners.forEach(fn => fn());
  170. processQueue();
  171. }
  172. function runTask(key, task) {
  173. if (hasError) return;
  174. var taskCallback = (0, _onlyOnce2.default)((err, ...result) => {
  175. runningTasks--;
  176. if (err === false) {
  177. canceled = true;
  178. return;
  179. }
  180. if (result.length < 2) {
  181. [result] = result;
  182. }
  183. if (err) {
  184. var safeResults = {};
  185. Object.keys(results).forEach(rkey => {
  186. safeResults[rkey] = results[rkey];
  187. });
  188. safeResults[key] = result;
  189. hasError = true;
  190. listeners = Object.create(null);
  191. if (canceled) return;
  192. callback(err, safeResults);
  193. } else {
  194. results[key] = result;
  195. taskComplete(key);
  196. }
  197. });
  198. runningTasks++;
  199. var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]);
  200. if (task.length > 1) {
  201. taskFn(results, taskCallback);
  202. } else {
  203. taskFn(taskCallback);
  204. }
  205. }
  206. function checkForDeadlocks() {
  207. // Kahn's algorithm
  208. // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
  209. // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
  210. var currentTask;
  211. var counter = 0;
  212. while (readyToCheck.length) {
  213. currentTask = readyToCheck.pop();
  214. counter++;
  215. getDependents(currentTask).forEach(dependent => {
  216. if (--uncheckedDependencies[dependent] === 0) {
  217. readyToCheck.push(dependent);
  218. }
  219. });
  220. }
  221. if (counter !== numTasks) {
  222. throw new Error('async.auto cannot execute tasks due to a recursive dependency');
  223. }
  224. }
  225. function getDependents(taskName) {
  226. var result = [];
  227. Object.keys(tasks).forEach(key => {
  228. const task = tasks[key];
  229. if (Array.isArray(task) && task.indexOf(taskName) >= 0) {
  230. result.push(key);
  231. }
  232. });
  233. return result;
  234. }
  235. return callback[_promiseCallback.PROMISE_SYMBOL];
  236. }
  237. module.exports = exports['default'];