generate a promise under certain assumptions/choices; then if the result changes the assumptions, repeat the generation with the new information
182413
async function repeatablePromise (initialAssumptions, assumptionsFromResult, promiseGenerator) {
    let promise = promiseGenerator(initialAssumptions);
    let result = await promise;
    let finalAssumptions = assumptionsFromResult(result);
    if (JSON.stringify(initialAssumptions) === JSON.stringify(finalAssumptions)) {
        return promise;
    } else {
        return promiseGenerator(finalAssumptions);
    }
}
598819
function (args) {
            args = argsToArray(arguments);
            if (this.__fired) {
                throw new Error("Already fired!");
            }
            this.__results = args;
            this.__resolve();
            return this.promise();
        }
918907
function all (promises) {

    var done      = new promise.Promise,
        successes = [],
        failures  = [],
        failed    = false,
        completed = 0,
        total     = promises.length;

    if (promises.length === 0) {
        done.resolve([]);
        return done;
    }

    var check = function () {
        if (++completed < total) {
            return;
        }
        if (failures.length) {
            failures.successes = successes;
            done.reject(failures);
        }
        else {
            done.resolve(successes);
        }
    };

    for (var i = 0; i < total; i++) {
        promise.when(promises[i], function (result) {
            successes[i] = result;
            check();
        }, function (error) {
            failures[i] = error;
            check();
        });
    }

    return done;
}
713735
function IncomingPromise(responseStream, promiseHeaders) {
  var stream = new Readable();
  stream._read = noop;
  stream.push(null);
  stream._log = responseStream._log;

  IncomingRequest.call(this, stream);

  this._onHeaders(promiseHeaders);

  this._responseStream = responseStream;

  var response = new IncomingResponse(this._responseStream);
  response.once('ready', this.emit.bind(this, 'response', response));

  this.stream.on('promise', this._onPromise.bind(this));
}
75512
function wrapParsePromise(promise, parsePromise) {
      ['_rejected', '_rejectedCallbacks', '_resolved', '_resolvedCallbacks', '_result', 'reject', 'resolve']
        .forEach(function (prop) {
          promise[prop] = parsePromise[prop];
        });

      ['_continueWith', '_thenRunCallbacks', 'always', 'done', 'fail'].forEach(function (method) {
        promise[method] = wrap(parsePromise[method]);
      });

      ['then', 'catch'].forEach(function (method) {
        var func = promise[method];
        promise[method] = function wrappedAngularPromise() {
          var args = Array.prototype.slice.call(arguments, 0);
          var promise = func.apply(this, args);
          wrapParsePromise(promise, parsePromise);
          return promise;
        };
      });

      return promise;
    }
1009928
function then(resolver, onFulfilled, onRejected) {
        var res = new Resolver();
        var promise = createPromise(res);

        if (isFunction(onFulfilled)) {
            onFulfilled = wrapCallback(res, promise, onFulfilled);
        }
        else {
            // not function
            // 'return promise' must fulfill with the same value
            // when 'main promise' is resolved
            // see #2.2.7.3
            onFulfilled = function (data) {
                res.fulfill(data);
            };
        }
        addListener(resolver, STATUS.FULFILLED, onFulfilled);

        if (isFunction(onRejected)) {
            onRejected = wrapCallback(res, promise, onRejected);
        }
        else {
            // not function
            // 'return promise' must reject with the same reason
            // when 'main promise' is rejected
            // see #2.2.7.4
            onRejected = function (reason) {
                res.reject(reason);
            };
        }
        addListener(resolver, STATUS.REJECTED, onRejected);

        return promise;
    }
1152546
function shouldRegenerate(node, state) {
  if (node.generator) {
    if (node.async) {
      // Async generator
      return state.opts.asyncGenerators !== false;
    } else {
      // Plain generator
      return state.opts.generators !== false;
    }
  } else if (node.async) {
    // Async function
    return state.opts.async !== false;
  } else {
    // Not a generator or async function.
    return false;
  }
}
455108
function generate(target, data, done) {
        var files = this.files,
            dest = null,
            paths = [],
            promises = [],
            folders = [];

        //by default, we generate a table of contents called readme.md
        var options = this.options({
            contentsEnabled: true,
            contentsFile: 'readme.md',
            contentsTitle: 'Documentation',
            templateDir: null
        });

        //map the list of files we'll be generating documentation for
        files.forEach(function(group) {
            dest = group.dest;
            group.src.filter(function(file) {
                var obj = {
                    filename: path.basename(file),
                    folder: path.dirname(file),
                    path: file
                };

                if(options.pathFilter)
                    obj.folder = obj.folder.replace(options.pathFilter, '');

                folders.push(obj);
            });
        });

        //map the set of folders, sort, and generate documentation
        folders = _(folders)
            .groupBy(function(p) { return p.folder; })
            .sortBy(function(p) { return p.length && p[0].folder; })
            .map(function(group) {
                var file = group.length && group[0] || {};
                return {
                    name: file.folder,
                    path: file.path.replace(file.filename, ''),
                    files: group,
                    fileData: {}
                };
            })
            .each(function(folder) {
                var def = Q.defer();

                //queue the promise for the docs, and ensure the target exists (can safely run on an existing folder)
                promises.push(def.promise);
                grunt.file.mkdir(dest +'/'+ folder.name);

                //generate the docs for the folder, resolving the promise when complete
                jsdox.generateForDir(folder.path, dest +'/'+ folder.name, options.templateDir, def.resolve, function(file, fileData) {
                    folder.fileData[file] = fileData;
                });
            });

        //when all docs have been generated, build the table of contents, if needed (this stuff should be moved into a template)
        Q.all(promises).then(function() {
            if(!options.contentsEnabled) return done();

            var buf = [],
                w = function() { buf.push.apply(buf, arguments); };

            w(options.contentsTitle || 'Documentation', '===');

            folders.forEach(function(folder) {
                var docs = [];

                //derive the set of documents we *actually* generated docs for; that way we only add documented
                //code to the table of contents
                folder.files.forEach(function(file) {
                    //reset the path, pointing to the markdown file, and set the file data parsed by jsdox
                    file.path = path.join(file.folder, file.filename.replace('.js', '')).replace(/^\//, '');
                    file.data = folder.fileData[file.filename]||{};
                    if(grunt.file.exists(dest, file.path + '.md')) docs.push(file);
                });

                if(docs.length > 0) {
                    w(folder.name || 'Root', '---');
                    w('name | overview', ':-- | :--');
                    docs.forEach(function(file) {
                        w('['+ file.path +'.js]('+ file.path + '.md' + ') | '+ (file.data.overview?'_'+ file.data.overview +'_':''));
                    });
                    w('- - -');
                }

                w('\n');
            });

            //write out the table of contents, and complete the async generate task
            fs.writeFileSync(path.join(dest, (options.contentsFile || 'readme.md')), buf.join('\n'));
            done();
        });
    }
258613
function createPromiseWith(actual, expected, verb) {
  assertPromise(actual);
  const success = jasmine.createSpy('Promise success callback');
  const failure = jasmine.createSpy('Promise failure callback');

  actual.then(success, failure);
  createScope().$digest();

  const spy = verb === 'resolved' ? success : failure;
  let pass = false;
  let message = `Expected promise to have been ${verb} with ${jasmine.pp(expected)} but it was not ${verb} at all`;

  if (isJasmine2 ? spy.calls.any() : spy.calls.length) {
    const actualResult = isJasmine2 ? spy.calls.mostRecent().args[0] : spy.mostRecentCall.args[0];
    if (angular.isFunction(expected)) {
      expected(actualResult);
      pass = true;
    } else {
      pass = angular.equals(actualResult, expected);
    }

    message = `Expected promise {not} to have been ${verb} with ${jasmine.pp(expected)} but was ${verb} with \
${jasmine.pp(actualResult)}`;
  }

  return getResult(`to${verb === 'resolved' ? 'Resolve' : 'Reject'}With`, pass, message);
}
1178559
function become(newPromise) {
        resolvedPromise = newPromise;
        promise.source = newPromise;

        array_reduce(messages, function (undefined, message) {
            Q.nextTick(function () {
                newPromise.promiseDispatch.apply(newPromise, message);
            });
        }, void 0);

        messages = void 0;
        progressListeners = void 0;
    }
1112904
function promiseResult (options, data) {
		log(`promiseResult: data ${data}`);
		return new Promise((resolve, reject) => {
			/* Check cache to avoid I/O. */
			const cacheHit = checkCache(config, pattern);
			if (cacheHit !== RESPONSE_UNKNOWN) {
				log(`Cache hit: ${cacheHit}`);
				return resolve(cacheHit);
			}

			const req = https.request(options, (res) => {
				res.setEncoding('utf8');

				let response = '';
				res.on('data', (chunk) => {
					log(`Got data`);
					response += chunk;
				});

				res.on('end', () => {
					log(`end: I got ${JSON.stringify(response)}`);

					const result = serverResponseToRESPONSE(response);
					log(`end: result ${result}`);
					updateCache(config, postObject.pattern, result);

					if (result === RESPONSE_INVALID) {
						return reject(result);
					} else {
						return resolve(result);
					}
				});
			});

			req.on('error', (e) => {
				log(`Error: ${e}`);
				return reject(RESPONSE_INVALID);
			});

			// Write data to request body.
			log(`Writing to req:\n${data}`);
			req.write(data);
			req.end();
		});
	}
496739
@NotNull
	public static Promise<Void> repeat(@NotNull Supplier<Promise<Void>> supplier) {
		return Promise.ofCallback(cb ->
				repeatImpl(supplier, cb));
	}
56776
function evaluatePromise() {
  var promise = kew.defer();
  var args = utils.toArray(arguments);
  args.push(promise.makeNodeResolver());
  /*jshint validthis:true */
  evaluate.apply(this, args);
  return promise;
}
1296495
function (iter) {
      function continuer(verb, arg) {
        var result;
        try {
          result = iter[verb](arg);
        } catch (err) {
          return Promise.reject(err);
        }
        if (result.done) {
          return result.value;
        } else {
          return Promise.resolve(result.value).then(onFulfilled, onRejected);
        }
      }
      var onFulfilled = continuer.bind(continuer, "next");
      var onRejected = continuer.bind(continuer, "throw");
      return onFulfilled();
    }
829421
def build_promise(depending_job, param_key)
      Promise.new.tap do |promise|
        promise.assign_attributes(job_id: job.id, hash_field: param_key, result_key: result_key)
        depending_job.promise_ids << promise.id
      end
    end
35223
function (promises) {
            var count = promises.length;
            if (!count) {
                return null;
            }
            var defer = new Defer();
            for (var i = 0; i < promises.length; i++) {
                /*jshint loopfunc:true*/
                (function (promise, i) {
                    when(promise, function (value) {
                        promises[i] = value;
                        if (--count === 0) {
                            // if all is resolved
                            // then resolve final returned promise with all value
                            defer.resolve(promises);
                        }
                    }, function (r) {
                        // if any one is rejected
                        // then reject final return promise with first reason
                        defer.reject(r);
                    });
                }(promises[i], i));
            }
            return defer.promise;
        }
463175
function(onFulfilled, onRejected) {
            var curr = this;
            var next = new Promise();                                    /*  [Promises/A+ 2.2.7]  */
            curr.onFulfilled.push(
                resolver(onFulfilled, next, 'fulfill'));             /*  [Promises/A+ 2.2.2/2.2.6]  */
            curr.onRejected.push(
                resolver(onRejected,  next, 'reject'));             /*  [Promises/A+ 2.2.3/2.2.6]  */
            execute(curr);
            return next;                                       /*  [Promises/A+ 2.2.7, 3.3]  */
        }