查找相关的数据, 更新或者插入
@param {object} source source model
@param {string} model target model
@param {object|array} args 要生成的参数
@param {any} t 事务标志
@return {Promise.<void>}
@this model
506449
async function one2one (source, model, args = {}, t) {
  let sourceId = `${this.name}Id`
  let previous = await this.models[model].findOne({
    where: {[sourceId]: source.id},
    transaction: t
  })

  if (!args.hasOwnProperty(sourceId)) {
    args[sourceId] = source.id
  }
  let insert = await util.insertOrUpdate(this.models[model], args, t)

  if (insert) {
    await previous.update({[sourceId]: null}, {transaction: t})
  }
}
591391
function triggerPromise() {
        var me = this;
        var args = arguments;

        var canHandlePromise =
            this.children.indexOf("completed") >= 0 &&
            this.children.indexOf("failed") >= 0;

        var createdPromise = new PromiseFactory(function(resolve, reject) {
            // If `listenAndPromise` is listening
            // patch `promise` w/ context-loaded resolve/reject
            if (me.willCallPromise) {
                _.nextTick(function() {
                    var previousPromise = me.promise;
                    me.promise = function (inputPromise) {
                        inputPromise.then(resolve, reject);
                        // Back to your regularly schedule programming.
                        me.promise = previousPromise;
                        return me.promise.apply(me, arguments);
                    };
                    me.trigger.apply(me, args);
                });
                return;
            }

            if (canHandlePromise) {
                var removeSuccess = me.completed.listen(function () {
                    var args = Array.prototype.slice.call(arguments);
                    removeSuccess();
                    removeFailed();
                    resolve(args.length > 1 ? args : args[0]);
                });

                var removeFailed = me.failed.listen(function () {
                    var args = Array.prototype.slice.call(arguments);
                    removeSuccess();
                    removeFailed();
                    reject(args.length > 1 ? args : args[0]);
                });
            }

            _.nextTick(function () {
                me.trigger.apply(me, args);
            });

            if (!canHandlePromise) {
                resolve();
            }
        });

        // Ensure that the promise does trigger "Uncaught (in promise)" errors in console if no error handler is added
        // See: https://github.com/reflux/reflux-promise/issues/4
        createdPromise.catch(function() {});

        return createdPromise;
    }
537714
function Promise(handler, parent) {
  var me = this;

  if (!(this instanceof Promise)) {
    throw new SyntaxError('Constructor must be called with the new operator');
  }

  if (typeof handler !== 'function') {
    throw new SyntaxError('Function parameter handler(resolve, reject) missing');
  }

  var _onSuccess = [];
  var _onFail = [];

  // status
  this.resolved = false;
  this.rejected = false;
  this.pending = true;

  /**
   * Process onSuccess and onFail callbacks: add them to the queue.
   * Once the promise is resolve, the function _promise is replace.
   * @param {Function} onSuccess
   * @param {Function} onFail
   * @private
   */
  var _process = function (onSuccess, onFail) {
    _onSuccess.push(onSuccess);
    _onFail.push(onFail);
  };

  /**
   * Add an onSuccess callback and optionally an onFail callback to the Promise
   * @param {Function} onSuccess
   * @param {Function} [onFail]
   * @returns {Promise} promise
   */
  this.then = function (onSuccess, onFail) {
    return new Promise(function (resolve, reject) {
      var s = onSuccess ? _then(onSuccess, resolve, reject) : resolve;
      var f = onFail    ? _then(onFail,    resolve, reject) : reject;

      _process(s, f);
    }, me);
  };

  /**
   * Resolve the promise
   * @param {*} result
   * @type {Function}
   */
  var _resolve = function (result) {
    // update status
    me.resolved = true;
    me.rejected = false;
    me.pending = false;

    _onSuccess.forEach(function (fn) {
      fn(result);
    });

    _process = function (onSuccess, onFail) {
      onSuccess(result);
    };

    _resolve = _reject = function () { };

    return me;
  };

  /**
   * Reject the promise
   * @param {Error} error
   * @type {Function}
   */
  var _reject = function (error) {
    // update status
    me.resolved = false;
    me.rejected = true;
    me.pending = false;

    _onFail.forEach(function (fn) {
      fn(error);
    });

    _process = function (onSuccess, onFail) {
      onFail(error);
    };

    _resolve = _reject = function () { }

    return me;
  };

  /**
   * Cancel te promise. This will reject the promise with a CancellationError
   * @returns {Promise} self
   */
  this.cancel = function () {
    if (parent) {
      parent.cancel();
    }
    else {
      _reject(new CancellationError());
    }

    return me;
  };

  /**
   * Set a timeout for the promise. If the promise is not resolved within
   * the time, the promise will be cancelled and a TimeoutError is thrown.
   * If the promise is resolved in time, the timeout is removed.
   * @param {number} delay     Delay in milliseconds
   * @returns {Promise} self
   */
  this.timeout = function (delay) {
    if (parent) {
      parent.timeout(delay);
    }
    else {
      var timer = setTimeout(function () {
        _reject(new TimeoutError('Promise timed out after ' + delay + ' ms'));
      }, delay);

      me.always(function () {
        clearTimeout(timer);
      });
    }

    return me;
  };

  // attach handler passing the resolve and reject functions
  handler(function (result) {
    _resolve(result);
  }, function (error) {
    _reject(error);
  });
}
685422
function tryFn(fn, args) {
  try {
    return Promise.resolve(fn.apply(null, args));
  } catch (e) {
    return Promise.reject(e);
  }
}
761046
function createUpdateStream(origin, target, options, completeCb) {
    // console.log('[EntitySetAsyncView][createUpdateStream]', 'from', origin.cid, 'to', target.cid );
    // let source = origin.source(options);
    // let sink = target.sink({}, completeCb);
    options = { ...options, emitEntities: true };

    let args = [origin.source(options)];

    if (options.debug) {
        args.push(
            PullMap(val => {
                let [data, dataOptions] = val;
                console.log('[EntitySetAsyncView][>]', origin.cid, target.cid, stringify(data));
                return val;
            })
        );
    }

    if (options.query) {
        args.push(QueryFilter(options.query, options));
    }

    args.push(target.sink({ source: origin }, completeCb));

    return Pull.apply(null, args);
}
492030
function reloadState(model, notify) {
    return function reload() {
        let { pathname, histories } = model,
            method = actionTypes.replace;

        // 更新监听
        return notify({
            pathname, method, histories, length: histories.length
        });
    };
}
817684
function (args) {
  tgi.Model.call(this, args);
  this.modelType = "Actor";
  this.attributes.push(new tgi.Attribute('Name'));
  this.attributes.push(new tgi.Attribute('Born', 'Number'));
  this.attributes.push(new tgi.Attribute({name:'Today', type:'Date', hidden:'*'}));
  this.attributes.push(new tgi.Attribute('Sex'));
  this.attributes.push(new tgi.Attribute('Joystick','Boolean'));
}
684116
function async (f, args) {
    new Promise(invoke).then(function asyncFulfill () {
      return f.apply(null, args);
    });
  }
459143
public EventBus emitSync(ActEvent event, Object... args) {
        return _emitWithOnceBus(eventContextSync(event, args));
    }
926369
function (args, callback) {
        if (ternserver) {
          ternserver.request({
              query: {
                type: "implementation",  //$NON-NLS-1$
                file: args.meta.location,
                end: args.params.offset,
                guess: args.guess
              },
              files: args.files
            },
            function (error, impl) {
              if (error) {
                callback({request: 'implementation', error: error.message, message: Messages['failedToComputeImpl']}); //$NON-NLS-1$
              }
              if (impl && impl.implementation && typeof impl.implementation.start === 'number' && typeof impl.implementation.end === "number") {
                callback({request: 'implementation', implementation: impl.implementation}); //$NON-NLS-1$
              } else if (impl && impl.implementation && impl.implementation.origin) {
                callback({request: 'implementation', implementation: impl.implementation}); //$NON-NLS-1$
              } else {
                callback({request: 'implementation', implementation: null}); //$NON-NLS-1$
              }
            });
        } else {
          callback({request: 'implementation', message: Messages['failedToComputeImplNoServer']}); //$NON-NLS-1$
        }
      }
702752
function ArrayEmitter(...args) {

  // Need to generate an actual array here for proper behaviour (in a full ES6 environment we
  // should be able to subclass array. But alas)
  var arr = new Array(...args);

  // Non enumerable so that we can send the array over postMessage
  Object.defineProperty(arr, '$emitter', {
    enumerable: false,
    value: new EventEmitter()
  });

  // Generate our Array Emitter methods
  var ArrayEmitterMethods = {};
  ['on', 'once', 'addListener', 'removeListener'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        return this.$emitter[key](...args);
      }
    };
  });

  // These methods create new arrays
  ['reverse', 'sort', 'splice'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        var _emitter = this.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          ArrayProto[key].apply(this, args);
        });

        ArrayProto[key].apply(this, args);
        return this;
      }
    };
  });

  ['filter', 'map', 'slice'].forEach(function(key) {
    ArrayEmitterMethods[key] = {
      enumerable: false,
      value: function(...args) {
        var newArr = new ArrayEmitter();
        var _emitter = this.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          updateNewArr(ArrayProto[key].apply(this, args));
          newArr.$emitter.emit('update', newArr);
        });

        updateNewArr(ArrayProto[key].apply(this, args));

        function updateNewArr(arr) {
          newArr.length = 0;
          for (var i = 0; i < arr.length; i++) {
            newArr.push(arr[i]);
          }
        }

        return newArr;
      }
    };
  });

  ArrayEmitterMethods.concat = {
    enumerable: false,
    value: function(...args) {
      var newArr = new ArrayEmitter();
      var allArrs = [this, ...args];
      var qries = allArrs.filter((obj) => (Array.isArray(obj) && obj.$emitter));
      qries.forEach((_qry) => {
        var _emitter = _qry.$emitter;
        incrMaxListeners(_emitter);
        _emitter.on('update', () => {
          updateConcat();
          newArr.$emitter.emit('update', newArr);
        });
      });

      updateConcat();

      return newArr;

      function updateConcat() {
        var concatted = ArrayProto.concat.call(...allArrs);
        newArr.length = 0;
        newArr.push(...concatted);
      }
    }
  };

  Object.defineProperties(arr, ArrayEmitterMethods);

  return arr;
}
662787
function callService(service, emitter, channel, callback) {
    var argsValue = Array.prototype.slice.call(Array.prototype.slice.call(arguments)[4]);
    var callerFunc = arguments.callee.caller;
    var eventName = service.name || service._name;
    var callerArgNames = _retrieveArgumentNames(callerFunc);
    var props = {};
    for(var i = 0; i < callerArgNames.length - 1; i++) {
        props[callerArgNames[i]] = argsValue[i];
    }
    if (callback) {
        emitter.once(eventName, callback);
    }
    if (emitter.isReady(true)) {
        try {
            service({
                props: props,
                channel: channel,
                callback: createEventEmitterCallback(eventName, emitter)
            });
        } catch (err) {
            emitter.emit('error', err);
        }
    }
    return new Promise(function (fulfill, reject) {
        emitter.once('error', reject);
        emitter.once(eventName, function (result) {
            emitter.removeListener('error', reject);
            if (typeof result !== 'boolean' && result.instanceOf('mtproto.type.Rpc_error')) {
                reject(new Error(result.error_message));
            } else {
                fulfill(result);
            }
        });
    });
}
1183506
public EventBus emitAsync(EventObject event, Object... args) {
        return _emitWithOnceBus(eventContextAsync(event, args));
    }
896805
public static void main(String[] args){

        // Listeners are subscribed by passing them to the #subscribe() method
        bus.subscribe(new ListenerDefinition.SyncAsyncListener());

        // #subscribe() is idem-potent => Multiple calls to subscribe do NOT add the listener more than once (set semantics)
        Object listener = new ListenerDefinition.SyncAsyncListener();
        bus.subscribe(listener);
        bus.subscribe(listener);

        // Classes without handlers will be silently ignored
        bus.subscribe(new Object());
        bus.subscribe(new String());

        bus.publishAsync(new File("/tmp/random.csv")); //returns immediately, publication will continue asynchronously
        bus.post(new File("/tmp/random.csv")).asynchronously(); // same as above

        bus.publish("some message");   // will return after each handler has been invoked
        bus.post("some message").now(); // same as above


    }
930637
function publicModel(model, readyPromise) {
    var res = [];

    function find(filter) {
        var mergedFilter = _.merge({}, model.filter, filter);
        var filteredModel = getModel(model.io, model.name, model.itemDef, model.modelDef, mergedFilter);
        if (model.children.indexOf(filteredModel) === -1) model.children.push(filteredModel);

        return filteredModel;
    }


    function getByIds(ids) {
        var items = [];
        for (var i = 0; i < res.length; i++) {
            if (ids.indexOf(res[i].id) !== -1) items.push(res[i]);
        }
        return items;
    }

    utils.defineProperties(res, {
        _isModel: { value: true },
        name: { value: model.name },

        ready: { value: readyPromise },

        create: { value: function(props) {
            props = props || {};

            var item = modelItem(props, model);
            item.ready = item.update(props).then(function() {
                model._addItem(item);
            });
            return item;
        } },

        itemById: { value: function(id) {
            for (var i = 0; i < this.length; i++) {
                if (this[i].id === id) return this[i];
            }
            return false;
        } },

        find: { value: find },
        filter: { value: find },

        findOne: { value: function(filter) {
            return find(filter).then(function(val) {
                if (val.length) return val[0];
                return false;
            });
        } },

        refresh: { value: function() {
            return Promise.all(_.map(this, function(item) {
                return item.refresh();
            }));
        } },

        then: { value: function() {
            return readyPromise.then.apply(readyPromise, arguments);
        } },

        catch: { value: function() {
            return readyPromise.catch.apply(readyPromise, arguments);
        } },

        /**
         * Override array modification properties
         */

        _pop: { value: arrayPop },

        pop: { value: function() {
            var lastItem = arrayPop.call(this);
            lastItem.delete();
            return lastItem;
        } },

        _push: { value: arrayPush },

        push: { value: function() {
            for (var i = 0; i < arguments.length; i++) {
                this.create(arguments[i]);
            }
            return this.length;
        } },

        _shift: { value: arrayShift },

        shift: { value: function() {
            var firstItem = arrayShift.call(this);
            firstItem.delete();
            return firstItem;
        } },

        _splice: { value: arraySplice },

        splice: { value: function(start, deleteCount) {
            var items = _.map(arraySlice.call(arguments, 2), function(itm) {
                var item = modelItem(itm, model);
                item.ready = item.update(itm);
                return item;
            });

            items.unshift(start, deleteCount);

            var removed = arraySplice.apply(this, items);
            for (var i = 0; i < removed.length; i++) removed.delete();
            return removed;
        } },

        _unshift: { value: arrayUnshift },

        unshift: { value: function() {
            return arrayUnshift.apply(this, _.map(arguments, function(itm) {
                var item = modelItem(itm, model);
                item.ready = item.update(itm);
                return item;
            }));
        } },

        __connection: { value: model.name }
    });

    //Object.defineProperties(res, );

    _.merge(res, utils.createCalculateProperty(function(previous, flags) {
        if (!previous) return;

        var isArray = _.isArray(previous), prevId;
        if (isArray) {
            prevId = _.map(previous, function(val) {
                if (_.isNumber(val)) return val;
                return val.id;
            });
        } else prevId = [_.isNumber(previous) ? previous : previous.id];

        return readyPromise.then(function() {
            var itms = getByIds(prevId);

            function getItems() {
                if (isArray) return { _stWrapped: true, val: itms};

                return { _stWrapped: true, val: itms.length ? itms[0] : null };
            }

            if (!flags.noRefresh) {
                return Promise.all(_.map(itms, function(item) {
                    return item.refresh();
                })).then(getItems);
            }

            return getItems();
        });
    }.bind(this)));

    return res;
}
265229
function(file, args) {
    return new Promise(function(resolve, reject) {
      var child = spawn(file, args, { stdio: 'inherit' });
      child.on('error', reject);
      child.on('close', resolve);
    });
  }
609741
function promiseGenerator(arr) {
  const data = [];
  const last = Symbol('last');
  
  // 添加迭代队列，以获取最后一次的promise执行结果
  arr.push(last);

  return arr.reduce((sum, value, index) => {
    return sum.then((result) => {
      // 忽略初始数据，即Promise.resolve()的返回数据
      if (index !== 0) data.push(result);

      // 如果到最后一个节点，则完成迭代，返回总体数据
      if (value === last) return data;

      return value();
    })
  }, Promise.resolve())
}