executor for Promise() constructor - <this> is prebind array of [worker, taskOrder]
320482
function promise_executor(resolve, reject) {
	var worker = this[0], order = this[1]
	Promise.resolve(promise_static_member(worker, order) || order)
		.catch(kickTaskOrder.bind(this)) // yes, the <this> is prebind array
		.then(resolve, reject)
}
1119036
function init(options){

    return Promise.resolve()
      .then(function() {

        if(!_.get(parameters,'process.source')){
          return;
        }

        return Promise.resolve()
          .then(function() {
            return updateAllKeys(options);
          })
          .then(function() {
            return createMissingFolders(options);
          })
          .then(function() {
            return deleteUnused(options);
          })
          .then(function() {
            return deleteEmptyFolders(options);
          });

      })
      .then(function() {

        if(!_.get(parameters,'process.search')){
          return;
        }

        return require('./search')(util,options);

      })
      .then(function() {
        util.log('Sync is complete');
      });

  }
1142656
function(task, context, args) {
            // can used to default task
            if (!_.isFunction(task)) {
                args = task;
                task = null;
                context = null;
            }

            if (!_.isArray(args)) args = [args];

            var d = Q.defer();
            this.tasks.push({
                "task": task,
                "args": args || [],
                "context": context,
                "result": d
            });
            if (this.empty == true) {
                this.startNext();
            }
            return d.promise;
        }
995151
function setupMainThread () {

    // Send a message to a worker, and optionally get an async response
    // Arguments:
    //   - worker: one or more web worker instances to send the message to (single value or array)
    //   - method: the method with this name, specified with dot-notation, will be invoked in the worker
    //   - message: spread of arguments to call the method with
    // Returns:
    //   - a promise that will be fulfilled if the worker method returns a value (could be immediately, or async)
    //
    WorkerBroker.postMessage = function (worker, method, ...message) {
        // If more than one worker specified, post to multiple
        if (Array.isArray(worker)) {
            return Promise.all(
                worker.map(w => WorkerBroker.postMessage(w, method, ...message))
            );
        }

        // Parse options
        let options = {};
        if (typeof method === 'object') {
            options = method;
            method = method.method;
        }

        // Track state of this message
        var promise = new Promise((resolve, reject) => {
            messages[message_id] = { method, message, resolve, reject };
        });


        let payload, transferables = [];

        if (message && message.length === 1 && message[0] instanceof WorkerBroker.withTransferables) {
            transferables = message[0].transferables;
            message = message[0].value;
        }

        payload = {
            type: 'main_send',      // mark message as method invocation from main thread
            message_id,             // unique id for this message, for life of program
            method,                 // will dispatch to a function of this name within the worker
            message                 // message payload
        };

        if (options.stringify) {
            payload = JSON.stringify(payload);
        }

        worker.postMessage(payload, transferables.map(t => t.object));
        freeTransferables(transferables);
        if (transferables.length > 0) {
            log('trace', `'${method}' transferred ${transferables.length} objects to worker thread`);
        }

        message_id++;
        return promise;
    };

    // Add a worker to communicate with - each worker must be registered from the main thread
    WorkerBroker.addWorker = function (worker) {
        if (!(worker instanceof Worker)) {
            throw Error('Worker broker could not add non-Worker object', worker);
        }

        worker.addEventListener('message', function WorkerBrokerMainThreadHandler(event) {
            let data = ((typeof event.data === 'string') ? JSON.parse(event.data) : event.data);
            let id = data.message_id;

            // Listen for messages coming back from the worker, and fulfill that message's promise
            if (data.type === 'worker_reply') {
                // Pass the result to the promise
                if (messages[id]) {
                    if (data.error) {
                        messages[id].reject(data.error);
                    }
                    else {
                        messages[id].resolve(data.message);
                    }
                    delete messages[id];
                }
            }
            // Listen for messages initiating a call from the worker, dispatch them,
            // and send any return value back to the worker
            // Unique id for this message & return call to main thread
            else if (data.type === 'worker_send' && id != null) {
                // Call the requested method and save the return value
                let result, error, target, method_name, method;
                try {
                    [method_name, target] = findTarget(data.method);
                    if (!target) {
                        throw Error(`Worker broker could not dispatch message type ${data.method} on target ${data.target} because no object with that name is registered on main thread`);
                    }

                    method = (typeof target[method_name] === 'function') && target[method_name];
                    if (!method) {
                        throw Error(`Worker broker could not dispatch message type ${data.method} on target ${data.target} because object has no method with that name`);
                    }

                    result = method.apply(target, data.message);
                }
                catch(e) {
                    // Thrown errors will be passed back (in string form) to worker
                    error = e;

                }
                // Send return value to worker
                let payload, transferables = [];

                // Async result
                if (result instanceof Promise) {
                    result.then((value) => {
                        if (value instanceof WorkerBroker.withTransferables) {
                            transferables = value.transferables;
                            value = value.value[0];
                        }

                        payload = {
                            type: 'main_reply',
                            message_id: id,
                            message: value
                        };
                        worker.postMessage(payload, transferables.map(t => t.object));
                        freeTransferables(transferables);
                        if (transferables.length > 0) {
                            log('trace', `'${method_name}' transferred ${transferables.length} objects to worker thread`);
                        }

                    }, (error) => {
                        worker.postMessage({
                            type: 'main_reply',
                            message_id: id,
                            error: (error instanceof Error ? `${error.message}: ${error.stack}` : error)
                        });
                    });
                }
                // Immediate result
                else {
                    if (result instanceof WorkerBroker.withTransferables) {
                        transferables = result.transferables;
                        result = result.value[0];
                    }

                    payload = {
                        type: 'main_reply',
                        message_id: id,
                        message: result,
                        error: (error instanceof Error ? `${error.message}: ${error.stack}` : error)
                    };
                    worker.postMessage(payload, transferables.map(t => t.object));
                    freeTransferables(transferables);
                    if (transferables.length > 0) {
                        log('trace', `'${method_name}' transferred ${transferables.length} objects to worker thread`);
                    }
                }
            }
        });

    };

    // Expose for debugging
    WorkerBroker.getMessages = function () {
        return messages;
    };

    WorkerBroker.getMessageId = function () {
        return message_id;
    };

}
532760
function(tasks, callback) {

      var keys; var length; var i; var results; var kind;
      var updated_tasks = [];
      var is_object;
      var counter = 0;

      if (isArray(tasks)) {

        length = tasks.length;
        results = [];

      } else if (isObject(tasks)) {

        is_object = true;
        keys = ObjectKeys(tasks);
        length = keys.length;
        results = {};

      } else {
        return callback();
      }

      for (i=0; i<length; i++) {

        if (is_object) {
          updated_tasks.push({ k: keys[i], t: tasks[keys[i]] });
        } else {
          updated_tasks.push({ k: i, t: tasks[i] });
        }

      }

      updated_tasks.forEach(function(task_object) {

        task_object.t(function(err, result) {
          if (err) return callback(err);

          results[task_object.k] = result;

          counter++;
          if (counter == length) callback(null, results);
        });

      });

    }
132402
private void processPredecessor(Task task, MapRow row)
   {
      Task predecessor = m_taskMap.get(row.getUUID("PREDECESSOR_UUID"));
      if (predecessor != null)
      {
         task.addPredecessor(predecessor, row.getRelationType("RELATION_TYPE"), row.getDuration("LAG"));
      }
   }
1235057
@Contract(pure = true)
	@NotNull
	public static <T> Promise<T[]> toArray(@NotNull Class<T> type, @NotNull List<? extends Promise<? extends T>> promises) {
		int size = promises.size();
		if (size == 0) return toArray(type);
		if (size == 1) return toArray(type, promises.get(0));
		if (size == 2) return toArray(type, promises.get(0), promises.get(1));

		@SuppressWarnings("unchecked") PromiseToArray<T> resultPromise = new PromiseToArray<>((T[]) Array.newInstance(type, size));

		for (int i = 0; i < size; i++) {
			Promise<? extends T> promise = promises.get(i);
			if (promise.isResult()) {
				resultPromise.accumulator[i] = promise.materialize().getResult();
				continue;
			}
			if (promise.isException()) return Promise.ofException(promise.materialize().getException());
			int index = i;
			resultPromise.countdown++;
			promise.whenComplete((result, e) -> {
				if (e == null) {
					resultPromise.processComplete(result, index);
				} else {
					resultPromise.tryCompleteExceptionally(e);
				}
			});
		}
		return resultPromise.countdown != 0 ? resultPromise : Promise.of(resultPromise.accumulator);
	}
97910
function executePromiseGetters(getters) {
  var concurrent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var stopped;
  var promise = new Promise(function (resolve, reject) {
    var r = [];
    var chunks = splitArray(getters, concurrent);
    var promise = Promise.resolve();
    chunks.forEach(function (chunk) {
      promise = promise.then(function (result) {
        if (result) {
          r.push.apply(r, _toConsumableArray(result));
        }

        if (stopped) {
          reject('stopped');
        } else {
          return Promise.all(chunk.map(function (v) {
            return v();
          }));
        }
      });
    });
    promise.then(function (result) {
      r.push.apply(r, _toConsumableArray(result));
      resolve(r);
    });
  });
  return {
    promise: promise,
    destroy: function destroy() {
      stopped = true;
    }
  };
}
1169706
function(resolve) {
    var self = this.chain()

    // if .find(null) was called
    if (self.getInternal('exec_null')) {
      return Promise.resolve(null)
    }

    var relation = self.getInternal('relation')

    if (relation && typeof relation.loadWithCollection === 'function') {
      const promise = relation.loadWithCollection(self)
      if (promise && promise.then) return promise.then(resolve)
    }

    var dataLoaded = self.getInternal('data_loaded')
    var options = self.getExecOptions()
    var data = {}

    if (dataLoaded) data.result = dataLoaded

    return self
      .callInterceptors('beforeFind', [options])
      .then(function() {
        return self.callInterceptors('onFind', [options, data], {
          executeInParallel: true
        })
      })
      .then(function() {
        return self.callInterceptors('afterFind', [data])
      })
      .then(function() {
        if (typeof resolve === 'function') return resolve(data.result)
        return data.result
      })
  }
721957
function async(makeGenerator, callback) {
  return function() {
    const generator = makeGenerator.apply(this, arguments);
    const handle = getHandle(generator, callback);
    try {
      return handle(generator.next());
    } catch(err) {
      return Promise.reject(err);
    }
  };
}
693868
@SuppressWarnings("unchecked")
	@NotNull
	public static <T> Iterator<Promise<T>> asPromises(@NotNull Iterator<? extends AsyncSupplier<? extends T>> tasks) {
		return transformIterator((Iterator<AsyncSupplier<T>>) tasks, AsyncSupplier::get);
	}
1010662
function next(i, p, task) {
        let iResult = task ? { value: task, done: false } : i.next();
        try {
            if (iResult.done) {
                publish($state);
                return;
            }
            const result = iResult.value($state, p);
            /* Promise(Like) */
            if (result && typeof result.then === 'function') {
                result.then(resolved, rejected);
                publish($state);
                return;
                function resolved(t) {
                    const _t = (typeof t === 'function') && t;
                    next(i, p, _t);
                }
                ;
                function rejected(err) {
                    publish($state, err);
                }
            }
            if (!iResult.done) {
                result && setState(result);
                next(i, p);
                return;
            }
        }
        catch (e) {
            publish($state, e);
        }
    }
158194
function Deferred () {
	var self      = this;

	this.promise  = promise.factory();
	this.onDone   = [];
	this.onAlways = [];
	this.onFail   = [];

	// Setting handlers to execute Arrays of Functions
	this.promise.then( function ( arg ) {
		promise.delay( function () {
			array.each( self.onDone, function ( i ) {
				i( arg );
			});

			array.each( self.onAlways, function ( i ) {
				i( arg );
			});

			self.onAlways = [];
			self.onDone   = [];
			self.onFail   = [];
		});
	}, function ( arg ) {
		promise.delay( function () {
			array.each( self.onFail, function ( i ) {
				i( arg );
			});

			array.each( self.onAlways, function ( i ) {
				i( arg );
			});

			self.onAlways = [];
			self.onDone   = [];
			self.onFail   = [];
		});
	});
}
729992
@Override
    public IPromise<T> awaitPromise(long timeout) {
        long endtime = 0;
        if ( timeout > 0 ) {
            endtime = System.currentTimeMillis() + timeout;
        }
        if ( Thread.currentThread() instanceof DispatcherThread ) {
            DispatcherThread dt = (DispatcherThread) Thread.currentThread();
            Scheduler scheduler = dt.getScheduler();
            int idleCount = 0;
            dt.__stack.add(this);
            while( ! isSettled() ) {
                if ( ! dt.pollQs() ) {
                    idleCount++;
                    scheduler.pollDelay(idleCount);
                } else {
                    idleCount = 0;
                }
                if ( endtime != 0 && System.currentTimeMillis() > endtime && ! isSettled() ) {
                    timedOut(Timeout.INSTANCE);
                    break;
                }
            }
            dt.__stack.remove(dt.__stack.size()-1);
            return this;
        } else {
            // if outside of actor machinery, just block
            CountDownLatch latch = new CountDownLatch(1);
            then( (res, err) -> {
                latch.countDown();
            });
            boolean timedOut = false;
            try {
                timedOut = ! latch.await(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if ( timedOut )
                timedOut(Timeout.INSTANCE);
            return this;
        }
    }
670934
@NotNull
	public static Promise<Void> all(@NotNull Iterator<? extends Promise<?>> promises) {
		if (!promises.hasNext()) return all();
		@NotNull PromiseAll<Object> resultPromise = new PromiseAll<>();
		while (promises.hasNext()) {
			Promise<?> promise = promises.next();
			if (promise.isResult()) continue;
			if (promise.isException()) return Promise.ofException(promise.materialize().getException());
			resultPromise.countdown++;
			promise.next(resultPromise);
		}
		return resultPromise.countdown != 0 ? resultPromise : Promise.complete();
	}
649591
function () {
		var i     = 0,
		    defer = deferred(),
		    args  = array.cast( arguments ),
		    nth;

		// Did we receive an Array? if so it overrides any other arguments
		if ( args[0] instanceof Array ) {
			args = args[0];
		}

		// How many instances to observe?
		nth = args.length;

		// None, end on next tick
		if ( nth === 0 ) {
			defer.resolve( null );
		}
		// Setup and wait
		else {
			array.each( args, function ( p ) {
				p.then( function () {
					if ( ++i === nth && !defer.isResolved()) {
						if ( args.length > 1 ) {
							defer.resolve( args.map( function ( obj ) {
								return obj.value || obj.promise.value;
							}));
						}
						else {
							defer.resolve( args[0].value || args[0].promise.value );
						}
					}
				}, function () {
					if ( !defer.isResolved() ) {
						if ( args.length > 1 ) {
							defer.reject( args.map( function ( obj ) {
								return obj.value || obj.promise.value;
							}));
						}
						else {
							defer.reject( args[0].value || args[0].promise.value );
						}
					}
				});
			});
		}

		return defer;
	}
140385
function (value) {
            var promise = this.promise, pendings;
            if ((pendings = promise[PROMISE_PENDINGS]) === false) {
                return null;
            }    // set current promise 's resolved value
                 // maybe a promise or instant value
            // set current promise 's resolved value
            // maybe a promise or instant value
            promise[PROMISE_VALUE] = value;
            pendings = pendings ? [].concat(pendings) : [];
            promise[PROMISE_PENDINGS] = false;
            promise[PROMISE_PROGRESS_LISTENERS] = false;
            util.each(pendings, function (p) {
                promiseWhen(promise, p[0], p[1]);
            });
            return value;
        }