Note that we're returning a Promise object here, and bypassing the
        helper functionality that normally sets the results struct from the
        returned object. Instead, we set _context.results directly inside of
        another promise
484452
def call(self, params, _context, **kwargs):
        ''''''

        assert len(params) == self.paramCount
        # using setattr because '=' is not allowed inside of lambdas
        return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
594304
function ( fn, context ) {

		// Initialize variables
		this.state = Promise.STATE.INITIALIZED;
		this.handlers = [];
		this.value = fn;

		// Rebind control functions to be run always on this promise
		this.resolve = this.resolve.bind( this );
		this.fulfill = this.fulfill.bind( this );
		this.reject = this.reject.bind( this );

		// Set fn and context
		if ( fn ) {
			if ( typeof fn !== 'function' ) throw new TypeError("fn is not a function");

			this.fn = fn;
			this.context = context || this;

			this.run();

		}

		return this;
	}
1153007
function fetchResults (searchText) {
    var items = $scope.$parent.$eval(itemExpr),
        term  = searchText.toLowerCase(),
        isList = angular.isArray(items),
        isPromise = !!items.then; // Every promise should contain a `then` property

    if (isList) onResultsRetrieved(items);
    else if (isPromise) handleAsyncResults(items);

    function handleAsyncResults(items) {
      if (!items) return;

      items = $q.when(items);
      fetchesInProgress++;
      setLoading(true);

      $mdUtil.nextTick(function () {
          items
            .then(onResultsRetrieved)
            .finally(function(){
              if (--fetchesInProgress === 0) {
                setLoading(false);
              }
            });
      },true, $scope);
    }

    function onResultsRetrieved(matches) {
      cache[term] = matches;

      // Just cache the results if the request is now outdated.
      // The request becomes outdated, when the new searchText has changed during the result fetching.
      if ((searchText || '') !== ($scope.searchText || '')) {
        return;
      }

      handleResults(matches);
    }
  }
504981
function getResult(attrNode, dataSourceName, context) {
    const resultId = attrNode.dataSources[dataSourceName].resultId;
    if (typeof resultId === 'undefined') {
        const attrPath = context.attrPath.length > 0 ? context.attrPath.join('.') : '{root}';
        throw new ImplementationError(`Result for "${attrPath}" (DataSource "${dataSourceName}") missing`);
    }
    return context.rawResults[resultId];
}
106071
function doResolve(result) {
  let self = this;
  if (result === self) {
    // Promise Standard 2.3.1
    return doReject.call(
      self,
      new TypeError("Can not resolve 'Promise' itself")
    );
  }
  // Promise Standard 2.3.3.2
  try {
    // Promise Standard 2.3.2 and 2.3.3 can be merge
    // if result is a thenable(.then)
    let then = safelyToThen(result);
    if (then) {
      // Promise Standard 2.3.3.3
      safelyToExecutor(self, then.bind(result));
    } else {
      // [[ async ]]
      setTimeout(function() {
        // commonly case
        if (self.currentState === Shared.PENDING) {
          self.currentState = Shared.FULFILLED;
          self.valOrErr = result;
          for (let i = 0; i < self.onFulfilledCallback.length; i++) {
            self.onFulfilledCallback[i](result);
          }
          self.onFulfilledCallback = [];
        }
      }, 0);
    }
    // case: when then(doResolve, doReject) -> asyncToResolveOrReject -> func(arg) -> return self
    return self;
  } catch (error) {
    return doReject.call(self, error);
  }
}
583226
function executeRelatedResult (result) {
    // load related records or resolve/with in parallel
    return Promise.all([
        this.executeRelatedResultResolve(result),
        this.executeRelatedResultWith(result),
    ])
    // resolve with result with related data merged in
    .then(() => result)
}
1054614
def dictPromise(m):
    
    ret = Promise()

    def handleSuccess(v, ret):
        for p in m.values():
            if not p.isFulfilled():
                return

        value = {}
        for k in m:
            value[k] = m[k].value
        ret.fulfill(value)

    for p in m.values():
        p.addCallback(lambda v: handleSuccess(v, ret))
        p.addErrback(lambda r: ret.reject(r))

    # Check to see if all the promises are already fulfilled
    handleSuccess(None, ret)

    return ret
281275
function(input, callback, context, remoteData)
  {
    var db = this;
    var promise = new Promise();

    promise.success( callback, context || db );

    function checkModel()
    {
      var result = db.parseModel( input, remoteData );

      if ( result !== false && !promise.isComplete() && db.initialized )
      {
        var remoteLoaded = db.remoteLoaded || !db.hasLoad( Load.All );
        var missingModel = (result === null || !result.$isSaved());
        var lazyLoad = db.hasLoad( Load.Lazy );

        if ( lazyLoad && remoteLoaded && missingModel )
        {
          if ( !result )
          {
            result = db.keyHandler.buildObjectFromKey( db.keyHandler.buildKeyFromInput( input ) );
          }

          result.$once( Model.Events.RemoteGets, function()
          {
            if ( !promise.isComplete() )
            {
              if ( isObject( input ) )
              {
                result.$set( input );
              }

              promise.resolve( result.$isSaved() ? result : null );
            }
          });

          result.$refresh( Cascade.All, db.fetchOptions );
        }
        else
        {
          promise.resolve( result );
        }
      }

      return promise.isComplete() ? false : true;
    }

    if ( checkModel() )
    {
      db.ready( checkModel, db, true );
    }

    return promise;
  }
977278
function setContext(req, res, next) {
    currentContext = {req: req, res: res};
    next();
}
899728
function cacheResults (result) {
    // JSON encode result
    try {
        var cacheValue = JSON.stringify(result)
    }
    catch (err) {
        // ignore errors
    }
    // cache value
    if (defined(cacheValue)) {
        // debug
        debug('view:id:collection:set', this.idCacheKey)
        // cache results
        return this.cache.redis.setAsync(this.idCacheKey, cacheValue)
    }
}
1257613
function wrappedFetch() {
  var wrappedPromise = {};

  var promise = new Promise(function (resolve, reject) {
    wrappedPromise.resolve = resolve;
    wrappedPromise.reject = reject;
  });

  var args = new Array(arguments.length);

  for (var i = 0; i < args.length; i++) {
    args[i] = arguments[i];
  }

  wrappedPromise.promise = promise;

  Promise.resolve().then(function () {
    return fetch.apply(null, args);
  }).then(function (response) {
    wrappedPromise.resolve(response);
  }).catch(function (error) {
    wrappedPromise.reject(error);
  });

  return wrappedPromise;
}
179991
function(future,
                        fulfillCallbacks,
                        rejectCallbacks,
                        setValue,
                        setError,
                        setState) {
  var isResolved = false;

  var resolver = this;
  var fulfill = function(value) {
    // console.log("queueing fulfill with:", value);
    async(function() {
      setState("fulfilled");
      setValue(value);
      // console.log("fulfilling with:", value);
      fulfillCallbacks.pump(value);
    });
  };
  var reject = function(reason) {
    // console.log("queuing reject with:", reason);
    async(function() {
      setState("rejected");
      setError(reason);
      // console.log("rejecting with:", reason);
      rejectCallbacks.pump(reason);
    });
  };
  var resolve = function(value) {
    if (isThenable(value)) {
      value.then(resolve, reject);
      return;
    }
    fulfill(value);
  };
  var ifNotResolved = function(func, name) {
    return function(value) {
      if (!isResolved) {
        isResolved = true;
        func(value);
      } else {
        if (typeof console != "undefined") {
          console.error("Cannot resolve a Promise multiple times.");
        }
      }
    };
  };

  // Indirectly resolves the Promise, chaining any passed Promise's resolution
  this.resolve = ifNotResolved(resolve, "resolve");

  // Directly fulfills the future, no matter what value's type is
  this.fulfill = ifNotResolved(fulfill, "fulfill");

  // Rejects the future
  this.reject = ifNotResolved(reject, "reject");

  this.cancel  = function() { resolver.reject(new Error("Cancel")); };
  this.timeout = function() { resolver.reject(new Error("Timeout")); };

  if (underTest) {
    Object.defineProperties(this, {
      _isResolved: _readOnlyProperty(function() { return isResolved; }),
    });
  }

  setState("pending");
}
1070819
function executeRelatedResultWith (result) {
    // skip if no with models specified
    if (!defined(this.args.with)) {
        return
    }
    // add related records keyed by related model name
    result._related = {}
    // load all related records
    return Promise.map(_.keys(this.args.with), relatedName => this.executeRelatedResultWithQuery(result, relatedName), {
        concurrency: this.model.concurrency,
    })
}
1344159
function resolveContext (emitter, context, storageKey) {
  // TODO: clean up - try to use internal context resolve more on no
  // use the one from on (resolve)
  // figure out why we cant use resolveContextSet since thats what it is
  if (context) {
    // this is lame stuff! should be in observable in some way...
    let base = emitter.parent.parent
    let type = emitter.key
    let setObj = { on: {} }
    setObj.on[type] = {}
    // base = base.set(setObj) // .on[type]
    emitter = (base.set(setObj) || base)._on[type]
  }
  if (!emitter.hasOwnProperty(storageKey)) {
    emitter.setKey(storageKey, {}, false)
  }
  return emitter
}
872959
function assertContext() {
  return new Promise(function(resolve, reject) {
    // Check if we're in an active session
    let d = process.domain
    if (d == null ||
        d.context == null ||
        d.context.bardo == null) {
      // Begin the session before proceeding
      return begin().then((ctx) => {
        resolve(ctx)
      }).catch(reject)
    }

    // Continue onwards with our active domain
    return resolve(d.context.bardo)
  })
}
348182
function collectionResultPost (context) {
    // if there are synchronous views then execute any post functions
    if (this.hasCollectionSynchronous) {
        _.each(this.modelViews.collection.synchronous, modelView => {
            // if view does not have post function do nothing
            if (!modelView.post) {
                return
            }
            // execute post function and merge result to context
            _.merge(context, modelView.post(context))
        })
    }
    // if there are asynchronous views then execute any post functions
    if (this.hasCollectionAsynchronous) {
        return Promise.all(_.map(this.modelViews.collection.asynchronous, modelView => {
            // if view does not have post function do nothing
            if (!modelView.post) {
                return
            }
            // execute post function
            return modelView.post({
                context: context,
                session: this.query.session,
            }).then(ctx => {
                _.merge(context, ctx)
            })
        }))
        // resolve with context
        .then(() => context)
    }
    // otherwise resolve with context
    else {
        return Promise.resolve(context)
    }
}
319669
def bind(self, context) -> None:
        

        # make a computation context based on the enclosing context.
        self.__computation_context = ComputationContext(self, context)

        # re-bind is not valid. be careful to set the computation after the data item is already in document.
        for variable in self.variables:
            assert variable.bound_item is None
        for result in self.results:
            assert result.bound_item is None

        # bind the variables
        for variable in self.variables:
            self.__bind_variable(variable)

        # bind the results
        for result in self.results:
            self.__bind_result(result)