Better method for simulating a remote call

@method simulateRemoteCall
@param {Object|Function} response
@param {number} [statusCode=200]
@param {string} [statusText]
@return {Promise}
437535
function (response, statusCode, statusText) {
    var adapter = this, responseFunction, isOk, shouldCopy, isInvalid;
    statusCode = statusCode || 200;
    statusText = statusText || HTTP_STATUS_MESSAGES[statusCode];
    isOk = Math.round(statusCode / 100) === 2;
    if (typeof response === 'function') {
      shouldCopy = true;
      responseFunction = bind(this, response);
    }
    else {
      isInvalid = response instanceof DS.InvalidError;
      if (isInvalid) {
        response = new DS.InvalidError(response.errors);
      }
      else {
        response = copy(response, true);
      }
      responseFunction = function () {
        return response;
      };
    }
    return new Ember.RSVP.Promise(function (resolve, reject) {
      var value, func, data;
      func = isOk ? resolve : reject;
      data = responseFunction();
      if (shouldCopy) {
        data = copy(data, true);
      }
      value = isOk ? data : (isInvalid ? data : {
        response:     data || {error: statusText},
        responseJSON: data || {error: statusText},
        status:       statusCode,
        statusText:   statusText
      });
      Ember.runInDebug(function () {
        console[isOk ? 'log' : 'error'](
          fmt('[dev-fixtures] Simulating %@ response:', isOk ? 'success' : 'error'),
          copy(response, true)
        );
      });
      if (adapter.get('simulateRemoteResponse')) {
        // Schedule with setTimeout
        later(null, func, value, adapter.get('latency'));
      }
      else {
        // Asynchronous, but at the of the run-loop with zero latency
        schedule('actions', null, func, value);
      }
    }, "DS: DevFixtureAdapter#simulateRemoteCall");
  }
419826
function PushBotsErrorStatus(response) {
  MessagingServiceStatus.call(this, 'pushbots');

  // There was an error when attempting to send message
  this.state.message = response.code + ': ' + response.message;

  // See https://pushbots.com/developer/api/1 for details
  if (response.statusCode == 400) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (response.statusCode == 401) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (response.statusCode == 405) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (response.statusCode == 409) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (response.statusCode == 429) this.state.code = this.StatusCodes.LIMIT_EXCEEDED;
  else if (response.statusCode == 507) this.state.code = this.StatusCodes.LIMIT_EXCEEDED;
  else if (response.statusCode >= 500 && response.statusCode < 600) this.state.code = this.StatusCodes.SERVICE_DOWN;
  else this.state.code = this.StatusCodes.DEFAULT;
}
275674
function get(url, successCallback, errorCallback) {
    const request = new XMLHttpRequest();

    request.open('GET', url, true);

    request.onreadystatechange = () => {
        if (request.readyState === 4) {
            /* Status 304 (Not Modified) is also a successful for the GET request. */
            if (((request.status >= 200) && (request.status < 300)) || (request.status === 304)) {
                successCallback(request.responseText);
            } else {
                console.error(`GET (${url}): error ${request.status} ${request.statusText}`);
                errorCallback(request.status, request.statusText);
            }
        }
    };

    request.send(null);
}
412973
private static CouchbaseResponse handleOtherResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg,
        ResponseStatus status, boolean seqOnMutation, String remoteHostname) {
        CouchbaseResponse response = null;
        ByteBuf content = msg.content();
        long cas = msg.getCAS();
        short statusCode = msg.getStatus();
        String bucket = request.bucket();

        if (request instanceof UnlockRequest) {
            response = new UnlockResponse(status, statusCode, bucket, content, request);
        } else if (request instanceof TouchRequest) {
            response = new TouchResponse(status, statusCode, bucket, content, request);
        } else if (request instanceof AppendRequest) {
            MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition());
            response = new AppendResponse(status, statusCode, cas, bucket, content, descr, request);
        } else if (request instanceof PrependRequest) {
            MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition());
            response = new PrependResponse(status, statusCode, cas, bucket, content, descr, request);
        } else if (request instanceof KeepAliveRequest) {
            releaseContent(content);
            response = new KeepAliveResponse(status, statusCode, request);
        } else if (request instanceof NoopRequest) {
            releaseContent(content);
            response = new NoopResponse(status, statusCode, request);
        } else if (request instanceof CounterRequest) {
            long value = status.isSuccess() ? content.readLong() : 0;
            releaseContent(content);

            MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition());
            response = new CounterResponse(status, statusCode, bucket, value, cas, descr, request);
        } else if (request instanceof StatRequest) {
            String key = null;
            if (msg.getKey() != null) {
                key = new String(msg.getKey(), CHARSET);
            }
            String value = content.toString(CHARSET);
            releaseContent(content);

            response = new StatResponse(status, statusCode, remoteHostname, key, value, bucket, request);
        } else if (request instanceof GetAllMutationTokensRequest) {
            // 2 bytes for partition ID, and 8 bytes for sequence number
            MutationToken[] mutationTokens = new MutationToken[content.readableBytes() / 10];
            for (int i = 0; i < mutationTokens.length; i++) {
                mutationTokens[i] = new MutationToken((long)content.readShort(), 0, content.readLong(), request.bucket());
            }
            releaseContent(content);
            response = new GetAllMutationTokensResponse(mutationTokens, status, statusCode, bucket, request);
        } else if (request instanceof ObserveRequest) {
            byte observed = ObserveResponse.ObserveStatus.UNKNOWN.value();
            long observedCas = 0;
            if (status.isSuccess()) {
                short keyLength = content.getShort(2);
                observed = content.getByte(keyLength + 4);
                observedCas = content.getLong(keyLength + 5);
            }
            releaseContent(content);
            response = new ObserveResponse(status, statusCode, observed, ((ObserveRequest) request).master(),
                    observedCas, bucket, request);
        } else if (request instanceof ObserveSeqnoRequest) {
            if (status.isSuccess()) {
                byte format = content.readByte();
                switch(format) {
                    case 0:
                        response = new NoFailoverObserveSeqnoResponse(
                            ((ObserveSeqnoRequest) request).master(),
                            content.readShort(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            status,
                            statusCode,
                            bucket,
                            request
                        );
                        break;
                    case 1:
                        response = new FailoverObserveSeqnoResponse(
                            ((ObserveSeqnoRequest) request).master(),
                            content.readShort(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            status,
                            statusCode,
                            bucket,
                            request
                        );
                        break;
                    default:
                        throw new IllegalStateException("Unknown format for observe-seq: " + format);
                }
            } else {
                response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), (short) 0, 0,
                    0, 0, status, statusCode, bucket, request);
            }
            releaseContent(content);
        }

        return response;
    }
288059
function WrappedResponse(msg, hdr, err, res) {
  this._msg = msg;
  this.headers = hdr;
  this.error = err;
  this.response = res;
}
472672
function RoostErrorStatus(response) {
  MessagingServiceStatus.call(this, 'roost');

  // There was an error when attempting to send message
  this.state.message = response.code ? 'Code: ' + response.code + '. ' : '';
  this.state.message += response.error;

  // Determine the correct status code
  // No code is being passed from Roost at this time, so we must depend on the error string
  if (response.error.match(/auth/g)) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (response.error.match(/Invalid/g)) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (response.error.match(/Incorrectly formatted/g)) this.state.code = this.StatusCodes.DATA_REJECTED;
  else this.state.code = this.StatusCodes.DEFAULT;
}
791271
function loadRemoteJson(options, done) {
	var requestOptions = {
		url: options.url,
		headers: options.headers
	};
	var error;

	request(requestOptions, function (err, response, body) {
		if (err) {
			return done(error);
		}
		if (response.statusCode < 200 || response.statusCode >= 300) {
			error = new Error('Remote JSON responded with ' + response.statusCode + ' status');
			error.status = response.statusCode;
			return done(error);
		}
		try {
			body = JSON.parse(body);
		} catch (err) {
			return done(err);
		}
		done(null, body);
	});
}
1034227
function ZeroPushErrorStatus(response) {
  MessagingServiceStatus.call(this, 'zeropush');

  // There was an error when attempting to send message
  this.state.message = response.name + ': ' + response.message;

  if (response.name === 'InvalidPayloadError') this.state.code = this.StatusCodes.DATA_REJECTED;
  else this.state.code = this.StatusCodes.DEFAULT;
}
514813
function request2response ( request ) {

    let headers = {},
        headersKeys = [],
        headersEntries = [];

    request.getAllResponseHeaders ().replace ( /^(.*?):\s*([\s\S]*?)$/gm, ( match, key, value ) => {
      key = key.toLowerCase ();
      headersKeys.push ( key );
      headersEntries.push ([ key, value ]);
      let prevValue = headers[key];
      headers[key] = prevValue ? `${prevValue},${value}` : value;
    });

    return {
      request,
      ok: ( request.status / 200 | 0 ) === 1, // 200-299
      status: request.status,
      statusText: request.statusText,
      url: request.responseURL,
      clone: () => fetch.request2response ( request ),
      text: () => Promise.resolve ( request.responseText ),
      json: () => Promise.resolve ( JSON.parse ( request.responseText ) ),
      blob: () => Promise.resolve ( new Blob ([ request.response ]) ),
      headers: {
        keys: () => headersKeys,
        entries: () => headersEntries,
        get: key => headers[key.toLowerCase ()],
        has: key => key.toLowerCase () in headers
      }
    };

  }
398672
function sendRequest(url) {
        return new Promise((resolve, reject) => {
            request(url, (error, response, body) => {
                    if (!error && response.statusCode == 200) {
                        if (body.errcode) {
                            console.warn(body.errmsg);
                            reject(body.errmsg);
                        }
                        else {
                            resolve(body);
                        }
                    }
                    else {
                        console.warn(error);
                        reject(error);
                    }
                }
            );
        });
    }
1154439
function request(method, address, body, options) {
  let timeout = null;
  return new Promise((resolve, reject) => {
    try {
      const opts = _.merge({}, this.options, options, url.parse(address), {
        method,
      });

      // handle optional timeout
      if (typeof opts.timeout === 'number') {
        setTimeout(() => {
          reject(new Error(`${method} "${address}" timed out`));
          timeout = null;
        }, Math.floor(opts.timeout));
      }

      // create some request middleware to potentially
      // add headers ahead of time for auth or set cors, etc.
      const before =
        typeof opts.before === 'function'
          ? opts.before.call(this.context, method, address, opts)
          : () => null;

      const proto = opts.protocol === 'https:' ? https : http;

      return Promise.resolve(before)
        .then(() => {
          clearTimeout(timeout);

          const req = proto.request(opts, res => {
            let data = '';
            res
              .on('data', d => {
                data += d;
              })
              .on('error', error => {
                clearTimeout(timeout);
                reject(error);
              })
              .on('end', () => {
                clearTimeout(timeout);
                const parsedData = processData(res, data, opts);
                return parsedData instanceof Error
                  ? reject(parsedData)
                  : resolve(parsedData);
              });
          });

          req.on('error', error => {
            clearTimeout(timeout);
            reject(error);
          });

          if (method === Method.PUT || method === Method.POST) {
            req.write(processBody(opts, body));
          }
          req.end();
        })
        .catch(error => {
          clearTimeout(timeout);
          return reject(error);
        });
    } catch (error) {
      clearTimeout(timeout);
      return reject(error);
    }
  });
}
344848
function transformResponse(transform) {

  assert.ok(transform);
  assert.ok(transform instanceof Function);

  var originalStatus, originalJson, reqClosure;

  return function (req, res, next) {
    originalStatus = res.status;
    originalJson = res.json;
    reqClosure = req;
    res.status = setStatus;
    res.json = sendJson;
    return next();
  }

  function setStatus(status) {
    this.__status = status;
    return this;
  }

  function sendJson(body) {
    this.__body = body;
    var B = new Bundle(transform, reqClosure, this);
    originalStatus.call(this, B.status);
    return originalJson.call(this, B.body);
  }

}
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;
  }
149408
function responsePromise(response) {
				response.status = response.status || 200;
				return $q(function(resolve, reject) {
					(response.status >= 200 && response.status <= 299 ? resolve : reject)(response);
				});
			}
1236460
function (args, result, func, extra) {
		return new SR.promise(function (resolve, reject) {
			UTIL.safeCall(func, args, result, function () {
				UTIL.safeCall(resolve);
			}, extra);
		});
	}
1235092
function () {
        if (req.status !== 200) {
          console.warn(req.responseText);
          return;
        }
        // Show the raw response text on page
        xmlOutput.textContent = req.responseText;
        // convert XML to javascript objects
        var json = sdmxmllib.mapSDMXMLResponse(req.responseText);
        // Convert to json and show on page
        jsonOutput.textContent = JSON.stringify(json, null, 2);
    }
1058371
public static <ReqT, RespT> ListenableFuture<RespT> futureUnaryCall(
      ClientCall<ReqT, RespT> call, ReqT req) {
    GrpcFuture<RespT> responseFuture = new GrpcFuture<>(call);
    asyncUnaryRequestCall(call, req, new UnaryStreamToFuture<>(responseFuture), false);
    return responseFuture;
  }