Mapping result value of promise to another value

@param res mapping function
@param <R> destination type
@return promise
199509
@ObjectiveCName("map:")
    public <R> Promise<R> map(final Function<T, R> res) {
        final Promise<T> self = this;
        return new Promise<>((PromiseFunc<R>) resolver -> {
            self.then(t -> {
                R r;
                try {
                    r = res.apply(t);
                } catch (Exception e) {
                    e.printStackTrace();
                    resolver.tryError(e);
                    return;
                }
                resolver.tryResult(r);
            });
            self.failure(e -> resolver.error(e));
        });
    }
1362705
function resolve(vResult0) {
			var fnThen;

			if (vResult0 === that) {
				reject(new TypeError("A promise cannot be resolved with itself."));
				return;
			}
			if (vResult0 instanceof SyncPromise) {
				if (vResult0.isFulfilled()) {
					resolve(vResult0.getResult());
					return;
				} else if (vResult0.isRejected()) {
					vResult0.caught(); // might have been uncaught so far
					reject(vResult0.getResult());
					return;
				} else {
					vResult0.caught(); // make sure it will never count as uncaught
					vResult0 = vResult0.getResult(); // unwrap to access native thenable
				}
			}

			iState = 0;
			vResult = vResult0;
			if (hasThen(vResult)) {
				try {
					fnThen = vResult.then;
				} catch (e) {
					// 2.3.3.2. If retrieving the property x.then results in a thrown exception e,
					// reject promise with e as the reason.
					reject(e);
					return;
				}
				if (typeof fnThen === "function") {
					call(fnThen.bind(vResult), resolve, reject);
					return;
				}
			}
			iState = 1;
			if (fnResolve) {
				fnResolve(vResult);
				fnReject = fnResolve = null; // be nice to the garbage collector
			}
		}
1231717
@Contract(pure = true)
	@NotNull
	public static <T> Promise<List<T>> toList(@NotNull Promise<? extends T> promise1, @NotNull Promise<? extends T> promise2) {
		return promise1.combine(promise2, (value1, value2) -> asList(value1, value2));
	}
46744
@SuppressWarnings("unchecked")
	@Contract(pure = true)
	@NotNull
	public static <T> Promise<T[]> toArray(@NotNull Class<T> type, @NotNull Promise<? extends T> promise1) {
		return promise1.map(value -> {
			@NotNull T[] array = (T[]) Array.newInstance(type, 1);
			array[0] = value;
			return array;
		});
	}
1335006
@Override
	public Promise get(String key) {
		if (status.get() == STATUS_CONNECTED) {
			try {
				return client.get(key).then(in -> {
					if (in != null) {
						byte[] source = in.asBytes();
						if (source != null) {
							try {
								Tree root = serializer.read(source);
								Tree content = root.get(CONTENT);
								if (content != null) {
									return content;
								}
								return root;
							} catch (Exception cause) {
								logger.warn("Unable to deserialize cached data!", cause);
							}
						}
					}
					return Promise.resolve((Object) null);
				});
			} catch (Exception cause) {
				logger.warn("Unable to get data from Redis!", cause);
			}
		}
		return Promise.resolve((Object) null);
	}
312741
function syncPromise(promise) {
  let isDone = false;
  let res, err;

  promise.then(
    value => {
      res = value;
      isDone = true;
    },
    error => {
      err = error;
      isDone = true;
    }
  );

  deasync.loopWhile(() => !isDone);

  if (err) {
    throw err;
  }

  return res;
}
232306
public static <A> A withQueryResult(QueryResult res,
                                        Function<java.sql.Connection, A> f) {

        return f.apply(connection(handleQuery((x, y) -> res)));
    }
397624
function resolvePromise(promise, state, value) {
        var onceWrapper = once();
        if (promise === value) {
            throw new TypeError(TYPE_ERROR);
        }
        if (promise[symbolState] === UNRESOLVED) {
            // should only get value.then once based on promise spec.
            var then = null;
            try {
                if (typeof value === 'object' || typeof value === 'function') {
                    then = value && value.then;
                }
            }
            catch (err) {
                onceWrapper(function () {
                    resolvePromise(promise, false, err);
                })();
                return promise;
            }
            // if (value instanceof ZoneAwarePromise) {
            if (state !== REJECTED && value instanceof ZoneAwarePromise &&
                value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
                value[symbolState] !== UNRESOLVED) {
                clearRejectedNoCatch(value);
                resolvePromise(promise, value[symbolState], value[symbolValue]);
            }
            else if (state !== REJECTED && typeof then === 'function') {
                try {
                    then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
                }
                catch (err) {
                    onceWrapper(function () {
                        resolvePromise(promise, false, err);
                    })();
                }
            }
            else {
                promise[symbolState] = state;
                var queue = promise[symbolValue];
                promise[symbolValue] = value;
                if (promise[symbolFinally] === symbolFinally) {
                    // the promise is generated by Promise.prototype.finally
                    if (state === RESOLVED) {
                        // the state is resolved, should ignore the value
                        // and use parent promise value
                        promise[symbolState] = promise[symbolParentPromiseState];
                        promise[symbolValue] = promise[symbolParentPromiseValue];
                    }
                }
                // record task information in value when error occurs, so we can
                // do some additional work such as render longStackTrace
                if (state === REJECTED && value instanceof Error) {
                    // check if longStackTraceZone is here
                    var trace = Zone.currentTask && Zone.currentTask.data &&
                        Zone.currentTask.data[creationTrace];
                    if (trace) {
                        // only keep the long stack trace into error when in longStackTraceZone
                        ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
                    }
                }
                for (var i = 0; i < queue.length;) {
                    scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
                }
                if (queue.length == 0 && state == REJECTED) {
                    promise[symbolState] = REJECTED_NO_CATCH;
                    try {
                        // try to print more readable error log
                        throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
                            (value && value.stack ? '\n' + value.stack : ''));
                    }
                    catch (err) {
                        var error_1 = err;
                        error_1.rejection = value;
                        error_1.promise = promise;
                        error_1.zone = Zone.current;
                        error_1.task = Zone.currentTask;
                        _uncaughtPromiseErrors.push(error_1);
                        api.scheduleMicroTask(); // to make sure that it is running
                    }
                }
            }
        }
        // Resolving an already resolved promise is a noop.
        return promise;
    }
359595
public static <R> Res<R> res(CloseFunction<R> closeFunction, R resource) {
    return new Res<>(closeFunction, resource);
  }
931918
function get (u, httpOptions) {
  return new Promise(function (resolve, reject) {
    // console.log('GET', u.href);

    var protocol = u.protocol === "https:" ? https : http;
    var req = protocol.get({
      hostname: u.hostname,
      port: u.port,
      path: u.path,
      auth: u.auth,
      protocol: u.protocol,
      headers: httpOptions.headers || {},
      withCredentials: httpOptions.withCredentials
    });

    if (typeof req.setTimeout === "function") {
      req.setTimeout(httpOptions.timeout);
    }

    req.on("timeout", function () {
      req.abort();
    });

    req.on("error", reject);

    req.once("response", function (res) {
      res.body = new Buffer(0);

      res.on("data", function (data) {
        res.body = Buffer.concat([res.body, new Buffer(data)]);
      });

      res.on("error", reject);

      res.on("end", function () {
        resolve(res);
      });
    });
  });
}
870605
public <R, V1, V2> Promise<MultipleResults2<V1, V2>, OneReject<R>, MasterProgress> when(AndroidExecutionScope scope, Promise<V1, ?, ?> promiseV1, Promise<V2, ?, ?> promiseV2) {
		Promise<MultipleResults2<V1, V2>, OneReject<R>, MasterProgress> p = super.when(promiseV1, promiseV2);
		return new AndroidDeferredObject<MultipleResults2<V1, V2>, OneReject<R>, MasterProgress>(p, scope).promise();
	}
1048919
public static DestinationRef unserializeFrom( RawDataBuffer in )
    {
        int type = in.readByte();
        if (type == NO_DESTINATION)
        	return null;
        
        String destinationName = in.readUTF();        
        switch (type)
        {
        	case TYPE_QUEUE : return new QueueRef(destinationName);
        	case TYPE_TOPIC : return new TopicRef(destinationName);
        	default:
        		throw new IllegalArgumentException("Unsupported destination type : "+type);
        }
    }
1100438
public static com.sun.javadoc.Type[] getTypes(DocEnv env, List<Type> ts,
                                                  com.sun.javadoc.Type res[]) {
        int i = 0;
        for (Type t : ts) {
            res[i++] = getType(env, t);
        }
        return res;
    }
144121
function getPromise(provider, extension) {
			var contentTypeIds = provider.getProperty("contentType") || provider.getProperty("contentTypes"), //$NON-NLS-1$ //$NON-NLS-0$
			    fileTypes = provider.getProperty("fileTypes"); // backwards compatibility //$NON-NLS-0$
			if (contentTypeIds) {
				return Deferred.when(contentTypeService.isSomeExtensionOf(contentType, contentTypeIds)).then(
					function (isMatch) {
						return isMatch ? provider : null;
					});
			} else if (extension && fileTypes && fileTypes.indexOf(extension) !== -1) {
				var d = new Deferred();
				d.resolve(provider);
				return d;
			}
			return null;
		}
341656
function getPromisedType(promise) {
            //
            //  { // promise
            //      then( // thenFunction
            //          onfulfilled: ( // onfulfilledParameterType
            //              value: T // valueParameterType
            //          ) => any
            //      ): any;
            //  }
            //
            if (isTypeAny(promise)) {
                return undefined;
            }
            if (promise.flags & 131072 /* Reference */) {
                if (promise.target === tryGetGlobalPromiseType()
                    || promise.target === getGlobalPromiseLikeType()) {
                    return promise.typeArguments[0];
                }
            }
            var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType();
            if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) {
                return undefined;
            }
            var thenFunction = getTypeOfPropertyOfType(promise, "then");
            if (!thenFunction || isTypeAny(thenFunction)) {
                return undefined;
            }
            var thenSignatures = getSignaturesOfType(thenFunction, 0 /* Call */);
            if (thenSignatures.length === 0) {
                return undefined;
            }
            var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */);
            if (isTypeAny(onfulfilledParameterType)) {
                return undefined;
            }
            var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
            if (onfulfilledParameterSignatures.length === 0) {
                return undefined;
            }
            return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true);
        }
115451
function getResults(result, objects) {
		
		// if there are no results, resolve an empty array
		if (!result) {
			return new Promise(function(resolve, reject) {
				resolve([]);
			});
		}
		
		// if the result object is undefined or not an array, make it one
		result.objects = result.objects || [];
		result.objects = Array.isArray(result.objects) ? result.objects : [result.objects];
		objects        = _.union(objects, result.objects);
		
		// if the result has a token, there are more results, continue to get them
		if (result.token) {
			return _client.method('ContinueRetrievePropertiesEx', {
				_this: _client._sc.propertyCollector,
				token: result.token
			})
			.then(function(results) {
				return getResults(results, objects);
			});
		}
		
		// if there are no more results, return the formatted results
		else {
			return new Promise(function(resolve, reject) {
				resolve(env.format(objects));
			});
		}
	}
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);
	}