Dispatch takes an incoming Task from the client and runs it on the
 server, returning the result to the client.
 Tasks returning a promise will wait to return.
775780
def dispatch(channel, message)
      # Dispatch the task in the worker pool.  Pas in the meta data
      @worker_pool.post do
        begin
          dispatch_in_thread(channel, message)
        rescue => e
          err = "Worker Thread Exception for #{message}\n"
          err += e.inspect
          err += e.backtrace.join("\n") if e.respond_to?(:backtrace)

          Volt.logger.error(err)
        end
      end
    end
932697
function AsyncQueue(tasks, fn) {
        // better compression for shrinking `this`
        var self = this;

        // TODO: exposing this is not safe
        self.tasks = [];
        self.callbacks = [];
        self.errors = [];

        // return values of Promise
        self.data = {};

        // resolved task index
        self.nextTask = 0;

        // resolved callback index
        self.nextCallback = 0;

        // -1 (default) means not waiting for AsyncQueue#then
        self.until = -1;

        // queue is executing callback
        self.digest = false;

        // add tasks and callbacks
        self.add(tasks).whenDone(fn);
    }
620266
def execute(self, resource, **kw):
        
        params = kw.pop('params', {})
        json = kw.pop('json', None)
        task = self.make_request(
            TaskRunFailed,
            method='create',
            params=params,
            json=json,
            resource=resource)

        timeout = kw.pop('timeout', 5)
        wait_for_finish = kw.pop('wait_for_finish', True)
        
        return TaskOperationPoller(
            task=task, timeout=timeout,
            wait_for_finish=wait_for_finish,
            **kw)
471471
def _result_handler(self, response: Dict[str, Any]):
        
        res = response.get("MESSAGE")
        ID = res.get("ID")
        result = res.get("RESULT")
        fut = self.tasks.get(ID)
        fut.set_result(result)
        return True
1020271
async def run_async(self, endpoint: str):
        
        self._connect(endpoint)

        # spawn an initial listen task
        listen_task = asyncio.ensure_future(self._socket.recv_multipart())
        task_list = [listen_task]

        while True:
            dones, pendings = await asyncio.wait(task_list, return_when=asyncio.FIRST_COMPLETED)

            # grab one "done" task to handle
            task_list, done_list = list(pendings), list(dones)
            done = done_list.pop()
            task_list += done_list

            if done == listen_task:
                try:
                    # empty_frame may either be:
                    # 1. a single null frame if the client is a REQ socket
                    # 2. an empty list (ie. no frames) if the client is a DEALER socket
                    identity, *empty_frame, msg = done.result()
                    request = from_msgpack(msg)

                    # spawn a processing task
                    task_list.append(asyncio.ensure_future(
                        self._process_request(identity, empty_frame, request)))
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'reception: {}'.format(str(e)))
                    else:
                        raise e
                finally:
                    # spawn a new listen task
                    listen_task = asyncio.ensure_future(self._socket.recv_multipart())
                    task_list.append(listen_task)
            else:
                # if there's been an exception during processing, consider reraising it
                try:
                    done.result()
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'dispatch: {}'.format(str(e)))
                    else:
                        raise e
1028719
def local_async(self, *args, **kwargs):
        '''
        
        '''
        local = salt.client.get_local_client(mopts=self.opts)
        ret = local.run_job(*args, **kwargs)
        return ret
673126
public void dispatchAsync(DispatchTask task, long delayMillis) {
		task.setScheduled(true);
		dispatch(task, delayMillis);
	}
179056
function (task, argument, callback) {
        var self = this;
        var queueArgument = {
            task: task,
            argument: argument
        };

        return promiseOrCallback(callback, function (resolve, reject) {
            self.taskQueue.push(queueArgument, function (error, result) {
                if (error) {
                    reject(error);
                } else {
                    resolve(result);
                }
            });
        });
    }
306478
function run(index) {
        if (index >= len || error) return Promise.resolve();
        next += 1;

        try {
          return Promise.resolve(iterator(arr[index], index)).then((ret) => {
            result[index] = ret;
            return run(next);
          }, (err) => {
            error = err;
            return Promise.reject(err);
          });
        } catch (e) {
          return Promise.reject(e);
        }
      }
774676
function task(callback) {
	// spawn phantomas process
	var child = phantomas(url, options, function(err, data, results) {
		callback(
			null, // pass null even in case of an error to continue async.series processing (issue #380)
			[err, results]
		);
	});

	child.on('progress', function(progress, inc) {
		if (bar) {
			bar.tick(inc);
		}
	});

	// pipe --verbose messages to stderr
	child.stderr.pipe(process.stderr);
}
1219234
async function execTasks(tasks, taskType) {
  debug(`execTasks: called for ${taskType}`);
  if (!(_.isEmpty(tasks))) {
    if (taskType) console.log(`running ${taskType}...`);
    const output = await Promise.mapSeries(tasks, async(task) => {
      const result = await execTask(task);
      if (_.isString(result.stdout) && (!_.isEmpty(result.stdout)))
        console.log(result.stdout.trim());
      if (_.isString(result.stderr) && (!_.isEmpty(result.stderr)))
        console.log(result.stderr.trim());
      return result;
    });
    return output;
  }
  debug("execTasks: nothing to do; resolving");
  return;
}
955960
def enqueue(self, method, *args, **kwargs):
        
        if not hasattr(method, "__call__"):
            raise ValueError(
                "{0} has no __call__ member.".format(method.__name__)
            )

        # Prepare the future result object
        future = FutureResult(self._logger)

        # Use a lock, as we might be "resetting" the queue
        with self.__lock:
            # Add the task to the queue
            self._queue.put((method, args, kwargs, future), True, self._timeout)
            self.__nb_pending_task += 1

            if self.__nb_pending_task > self.__nb_threads:
                # All threads are taken: start a new one
                self.__start_thread()

        return future
589915
def runTask(self, task, timeout=None):
        
        # Initialize the task.
        task.initialize(self)

        # Start the task.
        task.start()

        # Lets other threads run
        time.sleep(0)

        # Wait for it to finish.
        res = task.wait(timeout=timeout)

        # Now we're done
        return res
1176915
function processTask() {
        setTimeout(function() {
            if (isBusy || queue.length === 0) {
                return;
            }

            isBusy = true;

            var next = queue.shift(),
                result,
                error;

            Platform.async(function(callback) { // Start a promise chain
                callback();
            })().then(function() {
                return next.task(); // Run the task
            }).then(function(res) { // task completed successfully
                isBusy = false;
                processTask();
                next.callback(null, res); // resolve the promise returned by the run function
            }, function(err) { // task failed
                isBusy = false;
                processTask();
                next.callback(err); // reject the promise returned by the run function
            });
        }, 0);
    }
448615
function handleExecResult(m, workerIdx) {
	var job = jobs[m.context.jobID];
		
	job.cb(m.err, m.result);

	// Worker is finished.
	workerJobCount[workerIdx]--;
	dispatchWorkItems();
}
472974
function dispatchResult (error, data) {
    if (_cb.beforeAll) { _cb.beforeAll() }

    if (_cb.returnForAll) {
      _cb.returnForAll(error, data)
    } else if (!_isNullOrEmptyArray(error)) {
      var _error = _normalizeError(error)
      if (!_isNullOrEmptyArray(data)) {
        processErrorAndData(_error, data)
      } else {
        processError(_error)
      }
    } else {
      if (!_isNullOrEmptyArray(data)) {
        processData(data)
      } else {
        processNotFound()
      }
    }

    if (_cb.afterAll) { _cb.afterAll() }
  }
921830
def dispatch_operation(self, operation, request, path_args):
        # type: (Operation, BaseHttpRequest, Dict[str, Any]) -> Tuple[Any, Optional[HTTPStatus], Optional[dict]]
        
        try:
            # path_args is passed by ref so changes can be made.
            for middleware in self.middleware.pre_dispatch:
                middleware(request, path_args)

            resource = operation(request, path_args)

            for middleware in self.middleware.post_dispatch:
                resource = middleware(request, resource)

        except ImmediateHttpResponse as e:
            # An exception used to return a response immediately, skipping any
            # further processing.
            return e.resource, e.status, e.headers

        except ValidationError as e:
            # A validation error was raised by a resource.
            if hasattr(e, 'message_dict'):
                resource = Error.from_status(HTTPStatus.BAD_REQUEST, 0, "Failed validation", meta=e.message_dict)
            else:
                resource = Error.from_status(HTTPStatus.BAD_REQUEST, 0, str(e))
            return resource, resource.status, None

        except NotImplementedError:
            resource = Error.from_status(HTTPStatus.NOT_IMPLEMENTED, 0, "The method has not been implemented")
            return resource, resource.status, None

        except Exception as e:
            if self.debug_enabled:
                # If debug is enabled then fallback to the frameworks default
                # error processing, this often provides convenience features
                # to aid in the debugging process.
                raise

            resource = None
            # Fallback to the default handler
            if resource is None:
                resource = self.handle_500(request, e)

            return resource, resource.status, None

        else:
            return resource, None, None