Class in Sqimitive.Async Fetch

class Sqimitive.Async.Fetch extends Sqimitive.Async
Wrapper around a compatible _opt.function performing a single asynchronous request to a remote resource

Defined in: async.js, line 794

Description (skip)

Wrapper around a compatible _opt.function performing a single asynchronous request to a remote resource.

Example
var async = new Sqimitive.Async.Fetch({
  function: fetch,
  url: '//api.moe/v1/',
  method: 'POST',
  body: new URLSearchParams({moe: 'please!'}),
})

async.whenSuccess(function () {
  this.response.json().then(console.dir)
})

Other notes:

Properties

defaultFunction

Modifiers: static

The function used by _fetch() when _opt.function is unset.

Defaults to ajax() of the global jQuery, Zepto or _ (nodash/extra provides no:Extra.ajax()) or the native fetch(), whichever is available (in this order). This makes Fetch suitable for use in a web browser with zero configuration. In other environments client must either set defaultFunction (provided nobody else does so and the value fits all other clients) or supply _opt.function to every instance of Fetch.

Changes to defaultFunction take effect on next request (new Fetch).

Defined in: async.js, line 1005

_opt

Modifiers: protected

Members
Name Types Notes
functionfunction The backend doing actual fetching (e.g. jq:ajax() or browser’s fetch()).
null = defaultFunction
* Options given to function

Usually you want to set at least url (required by both ajax() and fetch()).

method/body (fetch()-style) default to values of type/data (ajax()-style).

Don’t set context (always this), success/error (use whenSuccess(), etc.), signal (use abort()).

Defined in: async.js, lines 851-854 (4 lines) • Show code

_opt: {
  function: null,
  // + ajax()/fetch() options
},
request

from readOnly

May only be read, not changed.

Available after init(). Result of _fetch(): native or wrapped XMLHttpRequest (as returned by ajax()) or Promise (fetch()).

Defined in: async.js, line 818Show code

request: null,
requestError

from readOnly

May only be read, not changed.

Available once not isSuccessful(). For ajax() this is whatever was given to the error callback (may be even unset/falsy). For (fetch()) this is either Response (request completed successfully but with HTTP status outside of 200-299; !requestError.ok) or Error (request didn’t complete).

Not to be confused with the Async.error event/method.

Defined in: async.js, line 828Show code

requestError: null,
response

from readOnly

May only be read, not changed.

Available once isSuccessful(). Value of request’s response... property (ajax()) or Response (fetch()).

Defined in: async.js, line 833Show code

response: null,

Methods

_assign ( obj )

Modifiers: protected

Sets response value based on properties of obj when this is about to become isSuccessful().

Base implementation is suitable for supported defaultFunction-s.

If overriding _assign(), avoid reading response data of the same (XMLHttpRequest) request multiple times because browsers parse it on every access. For example, 100 reads on xhr.response are 100 times slower than reading xhr.response once and using that copy for subsequent access. This is especially noticeable on huge JSONs where each read may take seconds.

Defined in: async.js, lines 975-1000 (26 lines) • Show code

_assign: function (obj) {
  if ('responseJSON' in obj) {
    var resp = obj.responseJSON   // non-standard jQuery field
  } else {
    switch (obj.responseType) {
      case '':
      case 'document':
        // Always a Document on a valid response.
        if (obj.responseXML) {
          resp = obj.responseXML
          break
        }
      case 'text':
        // Reading responseXML or responseText with mismatching responseType
        // produces an exception.
        resp = obj.responseText
        break
      default:
        //! +ig
        // Can be null for a valid JSON response if the fetched file's
        // contents is "null".
        resp = ('response' in obj) ? obj.response : obj /*fetch()'s Response*/
    }
  }
  this.response = resp
},
_fetch ( options )

Modifiers: protected

Fires off the request using options. Must either set response or return its new value.

Base implementation calls _opt.function or defaultFunction, giving it options. If result has then function (Promise), hooks it in order to call optionssuccess/error. error is also called if Promise fulfills with Response.ok of false.

ExampleIf using fetch(), request is Promise by default. You can replace it with a more useful Request by changing _opt.function or defaultFunction like so:
Async.Fetch.defaultFunction = function (options) {
  return fetch(options.context.request = new Request(options))
}

Defined in: async.js, lines 953-962 (10 lines) • Show code

_fetch: function (options) {
  var func = this.get('function') || this.constructor.defaultFunction
  var res = func(options)
  if (typeof res.then == 'function') {
    res.then(function (resp) {
      (resp.ok ? options.success : options.error)(resp, resp)
    }, options.error.bind(null, null))
  }
  return res
},
abort ( [reason] )

Aborts the request and fails this Async or does nothing if not isLoading().

Arguments
Name Types Notes
reasonmixed Used by fetch(), defaults to AbortError
omitted
Result Types
Types Notes
this

Defined in: async.js, line 861

readyStateText ( )

Returns a symbolic value for request.readyState if using ajax().

Result Types
Types Notes
string like LOADING
empty fetch() provides no such info

Defined in: async.js, lines 889-892 (4 lines) • Show code

readyStateText: function () {
  var states = ['UNSENT', 'OPENED', 'HEADERS_RECEIVED', 'LOADING', 'DONE']
  return this.request && states[this.request.readyState] || ''
},