⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 async.rst

📁 Ajax下日志框架
💻 RST
📖 第 1 页 / 共 2 页
字号:
.. title:: MochiKit.Async - manage asynchronous tasksName====MochiKit.Async - manage asynchronous tasksSynopsis========::    var url = "/src/b/bo/bob/MochiKit.Async/META.json";    /*        META.json looks something like this:        {"name": "MochiKit", "version": "0.5"}    */    var d = loadJSONDoc(url);    var gotMetadata = function (meta) {        if (MochiKit.Async.VERSION == meta.version) {            alert("You have the newest MochiKit.Async!");        } else {            alert("MochiKit.Async "                 + meta.version                + " is available, upgrade!");        }    };    var metadataFetchFailed = function (err) {      alert("The metadata for MochiKit.Async could not be fetched :(");    };    d.addCallbacks(gotMetadata, metadataFetchFailed);      Description===========MochiKit.Async provides facilities to manage asynchronous(as in AJAX [1]_) tasks. The model for asynchronous computationused in this module is heavily inspired by Twisted [2]_.Dependencies============- :mochiref:`MochiKit.Base`Overview========Deferred--------The Deferred constructor encapsulates a single value thatis not available yet. The most important example of thisin the context of a web browser would be an ``XMLHttpRequest``to a server. The importance of the Deferred is that itallows a consistent API to be exposed for all asynchronouscomputations that occur exactly once.The producer of the Deferred is responsible for doing allof the complicated work behind the scenes. This oftenmeans waiting for a timer to fire, or waiting for an event(e.g. ``onreadystatechange`` of ``XMLHttpRequest``). It could also be coordinating several events (e.g.``XMLHttpRequest`` with a timeout, or several Deferreds(e.g. fetching a set of XML documents that should be processed at the same time).Since these sorts of tasks do not respond immediately, theproducer of the Deferred does the following steps beforereturning to the consumer:1. Create a ``new`` :mochiref:`Deferred();` object and keep a reference   to it, because it will be needed later when the value is   ready.2. Setup the conditions to create the value requested (e.g.   create a new ``XMLHttpRequest``, set its    ``onreadystatechange``).3. Return the :mochiref:`Deferred` object.Since the value is not yet ready, the consumer attachesa function to the Deferred that will be called when thevalue is ready. This is not unlike ``setTimeout``, orother similar facilities you may already be familiar with.The consumer can also attach an "errback" to the:mochiref:`Deferred`, which is a callback for error handling.When the value is ready, the producer simply calls``myDeferred.callback(theValue)``. If an error occurred,it should call ``myDeferred.errback(theValue)`` instead.As soon as this happens, the callback that the consumerattached to the :mochiref:`Deferred` is called with ``theValue``as the only argument.There are quite a few additional "advanced" featuresbaked into :mochiref:`Deferred`, such as cancellation and callback chains, so take a look at the APIreference if you would like to know more!API Reference=============Errors------:mochidef:`AlreadyCalledError`:    Thrown by a :mochiref:`Deferred` if ``.callback`` or    ``.errback`` are called more than once.:mochidef:`BrowserComplianceError`:    Thrown when the JavaScript runtime is not capable of performing    the given function. Currently, this happens if the browser    does not support ``XMLHttpRequest``.:mochidef:`CancelledError`:    Thrown by a :mochiref:`Deferred` when it is cancelled,    unless a canceller is present and throws something else.:mochidef:`GenericError`:    Results passed to ``.fail`` or ``.errback`` of a :mochiref:`Deferred`    are wrapped by this ``Error`` if ``!(result instanceof Error)``.:mochidef:`XMLHttpRequestError`:    Thrown when an ``XMLHttpRequest`` does not complete successfully    for any reason. The ``req`` property of the error is the failed    ``XMLHttpRequest`` object, and for convenience the ``number``    property corresponds to ``req.status``.Constructors------------:mochidef:`Deferred()`:    Encapsulates a sequence of callbacks in response to a value that    may not yet be available. This is modeled after the Deferred class    from Twisted [3]_... _`Twisted`: http://twistedmatrix.com/    Why do we want this?  JavaScript has no threads, and even if it did,    threads are hard. Deferreds are a way of abstracting non-blocking    events, such as the final response to an ``XMLHttpRequest``.    The sequence of callbacks is internally represented as a list    of 2-tuples containing the callback/errback pair. For example,    the following call sequence::        var d = new Deferred();        d.addCallback(myCallback);        d.addErrback(myErrback);        d.addBoth(myBoth);        d.addCallbacks(myCallback, myErrback);    is translated into a :mochiref:`Deferred` with the following internal    representation::        [            [myCallback, null],            [null, myErrback],            [myBoth, myBoth],            [myCallback, myErrback]        ]    The :mochiref:`Deferred` also keeps track of its current status (fired).    Its status may be one of the following three values:                    ===== ================================        Value Condition        ===== ================================        -1    no value yet (initial condition)        0     success        1     error        ===== ================================        A :mochiref:`Deferred` will be in the error state if one of the following    conditions are met:        1. The result given to callback or errback is "``instanceof Error``"    2. The callback or errback threw while executing. If the thrown object       is not ``instanceof Error``, it will be wrapped with       :mochiref:`GenericError`.    Otherwise, the :mochiref:`Deferred` will be in the success state. The state    of the :mochiref:`Deferred` determines the next element in the callback    sequence to run.    When a callback or errback occurs with the example deferred chain, something    equivalent to the following will happen (imagine that exceptions are caught    and returned as-is)::        // d.callback(result) or d.errback(result)        if (!(result instanceof Error)) {            result = myCallback(result);        }        if (result instanceof Error) {            result = myErrback(result);        }        result = myBoth(result);        if (result instanceof Error) {            result = myErrback(result);        } else {            result = myCallback(result);        }        The result is then stored away in case another step is added to the    callback sequence. Since the :mochiref:`Deferred` already has a value    available, any new callbacks added will be called immediately.    There are two other "advanced" details about this implementation that are     useful:    Callbacks are allowed to return :mochiref:`Deferred` instances,    so you can build complicated sequences of events with (relative) ease.    The creator of the :mochiref:`Deferred` may specify a canceller. The    canceller is a function that will be called if    :mochiref:`Deferred.prototype.cancel` is called before the    :mochiref:`Deferred` fires. You can use this to allow an    ``XMLHttpRequest`` to be cleanly cancelled, for example. Note that    cancel will fire the :mochiref:`Deferred` with a    :mochiref:`CancelledError` (unless your canceller throws or returns    a different ``Error``), so errbacks should be prepared to handle that    ``Error`` gracefully for cancellable :mochiref:`Deferred` instances.:mochidef:`Deferred.prototype.addBoth(func)`:    Add the same function as both a callback and an errback as the    next element on the callback sequence. This is useful for code    that you want to guarantee to run, e.g. a finalizer.    If additional arguments are given, then ``func`` will be replaced    with :mochiref:`MochiKit.Base.partial.apply(null, arguments)`. This    differs from `Twisted`_, because the result of the callback or    errback will be the *last* argument passed to ``func``.    If ``func`` returns a :mochiref:`Deferred`, then it will be chained    (its value or error will be passed to the next callback). Note that    once the returned ``Deferred`` is chained, it can no longer accept new    callbacks.:mochidef:`Deferred.prototype.addCallback(func[, ...])`:    Add a single callback to the end of the callback sequence.    If additional arguments are given, then ``func`` will be replaced    with :mochiref:`MochiKit.Base.partial.apply(null, arguments)`. This    differs from `Twisted`_, because the result of the callback will    be the *last* argument passed to ``func``.    If ``func`` returns a :mochiref:`Deferred`, then it will be chained    (its value or error will be passed to the next callback). Note that    once the returned ``Deferred`` is chained, it can no longer accept new    callbacks.:mochidef:`Deferred.prototype.addCallbacks(callback, errback)`:    Add separate callback and errback to the end of the callback    sequence. Either callback or errback may be ``null``,    but not both.    If ``callback`` or ``errback`` returns a :mochiref:`Deferred`,    then it will be chained (its value or error will be passed to the    next callback). Note that once the returned ``Deferred`` is chained,    it can no longer accept new callbacks.:mochidef:`Deferred.prototype.addErrback(func)`:    Add a single errback to the end of the callback sequence.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -