281

jQuery 1.5は、新しいDeferredオブジェクトとアタッチされたメソッドをもたらし.whenます。.Deferred._Deferred

これまで使用したことがない人のために、ソースに.Deferred注釈を付けました。

これらの新しいメソッドの可能な使用法は何ですか、パターンにそれらを適合させるにはどうすればよいですか?

私はすでにAPIソースを読んだので、それが何をするかを知っています。私の質問は、これらの新機能を日常のコードでどのように使用できるかということです。

AJAXリクエストを順番に呼び出すバッファクラスの簡単な例があります。(次のものは前のものが終わった後に始まります)。

/* Class: Buffer
 *  methods: append
 *
 *  Constructor: takes a function which will be the task handler to be called
 *
 *  .append appends a task to the buffer. Buffer will only call a task when the 
 *  previous task has finished
 */
var Buffer = function(handler) {
    var tasks = [];
    // empty resolved deferred object
    var deferred = $.when();

    // handle the next object
    function handleNextTask() {
        // if the current deferred task has resolved and there are more tasks
        if (deferred.isResolved() && tasks.length > 0) {
            // grab a task
            var task = tasks.shift();
            // set the deferred to be deferred returned from the handler
            deferred = handler(task);
            // if its not a deferred object then set it to be an empty deferred object
            if (!(deferred && deferred.promise)) {
                deferred = $.when();
            }
            // if we have tasks left then handle the next one when the current one 
            // is done.
            if (tasks.length > 0) {
                deferred.done(handleNextTask);
            }
        }
    }

    // appends a task.
    this.append = function(task) {
        // add to the array
        tasks.push(task);
        // handle the next task
        handleNextTask();
    };
};

.Deferredとのデモンストレーションと可能な使用法を探してい.whenます。

の例を見るのも素敵でしょう._Deferred

jQuery.ajax例のために新しいソースにリンクすることは不正行為です。

操作が同期的に実行されるか非同期的に実行されるかを抽象化するときに、どのような手法が利用できるかに特に興味があります。

4

11 に答える 11

215

私が考えることができる最良のユースケースは、AJAX応答をキャッシュすることです。これは、トピックに関するRebeccaMurpheyの紹介投稿からの変更された例です。

var cache = {};

function getData( val ){

    // return either the cached value or jqXHR object wrapped Promise
    return $.when(
        cache[ val ] || 
        $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json',
            success: function( resp ){
                cache[ val ] = resp;
            }
        })
    );
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retrieved using an
    // XHR request.
});

基本的に、値がキャッシュからすぐに返される前に、値がすでに1回要求されている場合。それ以外の場合、AJAXリクエストはデータをフェッチしてキャッシュに追加します。$.when/はこれ.thenを気にしません。心配する必要があるのは.then()、どちらの場合もハンドラーに渡される応答を使用することだけです。jQuery.when()非Promise/DeferredをCompletedとして処理し、チェーン上で、.done()または.then()チェーン上ですぐに実行します。

遅延は、タスクが非同期で動作する場合と動作しない場合があり、その条件をコードから抽象化する場合に最適です。

$.whenヘルパーを使用した別の実例:

$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {

    $(tmpl) // create a jQuery object out of the template
    .tmpl(data) // compile it
    .appendTo("#target"); // insert it into the DOM

});
于 2011-02-02T12:57:51.747 に答える
79

これは、 ehyndの回答のようにAJAXキャッシュのわずかに異なる実装です。

fortuneRiceのフォローアップの質問で述べたように、ehyndの実装では、リクエストの1つが返される前にリクエストが実行された場合、実際には複数の同一のリクエストを防ぐことはできませんでした。あれは、

for (var i=0; i<3; i++) {
    getData("xxx");
}

「xxx」の結果が以前にキャッシュされていない場合は、3つのAJAXリクエストが発生する可能性があります。

これは、結果の代わりにリクエストのDeferredsをキャッシュすることで解決できます。

var cache = {};

function getData( val ){

    // Return a promise from the cache (if available)
    // or create a new one (a jqXHR object) and store it in the cache.
    var promise = cache[val];
    if (!promise) {
        promise = $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json'
        });
        cache[val] = promise;
    }
    return promise;
}

$.when(getData('foo')).then(function(resp){
    // do something with the response, which may
    // or may not have been retreived using an
    // XHR request.
});
于 2012-01-22T11:03:39.977 に答える
46

ミューテックスの代わりに据え置きを使用できます。これは基本的に、複数のajax使用シナリオと同じです。

MUTEX

var mutex = 2;

setTimeout(function() {
 callback();
}, 800);

setTimeout(function() {
 callback();
}, 500);

function callback() {
 if (--mutex === 0) {
  //run code
 }
}

延期

function timeout(x) {
 var dfd = jQuery.Deferred();
 setTimeout(function() {
  dfd.resolve();
 }, x);
 return dfd.promise();
}

jQuery.when(
timeout(800), timeout(500)).done(function() {
 // run code
});

Deferredをミューテックスとしてのみ使用する場合は、パフォーマンスへの影響に注意してください(http://jsperf.com/deferred-vs-mutex/2)。利便性、およびDeferredによって提供される追加の利点はそれだけの価値があり、実際の(ユーザー主導のイベントベースの)使用では、パフォーマンスへの影響は目立たないはずです。

于 2011-05-23T18:44:25.583 に答える
29

これは自己宣伝的な答えですが、私はこれを調査するために数か月を費やし、jQuery Conference SanFrancisco2012で結果を発表しました。

これがトークの無料ビデオです:

https://www.youtube.com/watch?v=juRtEEsHI9E

于 2012-10-10T22:18:53.517 に答える
20

私が良い目的を持っているもう1つの用途は、複数のソースからデータをフェッチすることです。以下の例では、クライアントとRESTサーバー間の検証のために、既存のアプリケーションで使用されている複数の独立したJSONスキーマオブジェクトをフェッチしています。この場合、すべてのスキーマが読み込まれる前に、ブラウザー側のアプリケーションがデータの読み込みを開始しないようにします。$ .when.apply()。then()はこれに最適です。then(fn1、fn2)を使用してエラー状態を監視するためのポインタを提供してくれたRaynosに感謝します。

fetch_sources = function (schema_urls) {
    var fetch_one = function (url) {
            return $.ajax({
                url: url,
                data: {},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
            });
        }
    return $.map(schema_urls, fetch_one);
}

var promises = fetch_sources(data['schemas']);
$.when.apply(null, promises).then(

function () {
    var schemas = $.map(arguments, function (a) {
        return a[0]
    });
    start_application(schemas);
}, function () {
    console.log("FAIL", this, arguments);
});     
于 2011-02-04T04:54:04.420 に答える
10

Deferredsを使用して、あらゆる種類の計算(通常、パフォーマンスを重視するタスクや長時間実行されるタスク)用のキャッシュを実装する別の例:

var ResultsCache = function(computationFunction, cacheKeyGenerator) {
    this._cache = {};
    this._computationFunction = computationFunction;
    if (cacheKeyGenerator)
        this._cacheKeyGenerator = cacheKeyGenerator;
};

ResultsCache.prototype.compute = function() {
    // try to retrieve computation from cache
    var cacheKey = this._cacheKeyGenerator.apply(this, arguments);
    var promise = this._cache[cacheKey];

    // if not yet cached: start computation and store promise in cache 
    if (!promise) {
        var deferred = $.Deferred();
        promise = deferred.promise();
        this._cache[cacheKey] = promise;

        // perform the computation
        var args = Array.prototype.slice.call(arguments);
        args.push(deferred.resolve);
        this._computationFunction.apply(null, args);
    }

    return promise;
};

// Default cache key generator (works with Booleans, Strings, Numbers and Dates)
// You will need to create your own key generator if you work with Arrays etc.
ResultsCache.prototype._cacheKeyGenerator = function(args) {
    return Array.prototype.slice.call(arguments).join("|");
};

このクラスを使用して(シミュレートされた重い)計算を実行する例を次に示します。

// The addingMachine will add two numbers
var addingMachine = new ResultsCache(function(a, b, resultHandler) {
    console.log("Performing computation: adding " + a + " and " + b);
    // simulate rather long calculation time by using a 1s timeout
    setTimeout(function() {
        var result = a + b;
        resultHandler(result);
    }, 1000);
});

addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

addingMachine.compute(1, 1).then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

同じ基になるキャッシュを使用して、Ajaxリクエストをキャッシュできます。

var ajaxCache = new ResultsCache(function(id, resultHandler) {
    console.log("Performing Ajax request for id '" + id + "'");
    $.getJSON('http://jsfiddle.net/echo/jsonp/?callback=?', {value: id}, function(data) {
        resultHandler(data.value);
    });
});

ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

ajaxCache.compute("anotherID").then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

このjsFiddleで上記のコードを試すことができます。

于 2012-01-22T14:14:41.590 に答える
9

1)これを使用して、コールバックの順序付けられた実行を確認します。

var step1 = new Deferred();
var step2 = new Deferred().done(function() { return step1 });
var step3 = new Deferred().done(function() { return step2 });

step1.done(function() { alert("Step 1") });
step2.done(function() { alert("Step 2") });
step3.done(function() { alert("All done") });
//now the 3 alerts will also be fired in order of 1,2,3
//no matter which Deferred gets resolved first.

step2.resolve();
step3.resolve();
step1.resolve();

2)アプリのステータスを確認するために使用します。

var loggedIn = logUserInNow(); //deferred
var databaseReady = openDatabaseNow(); //deferred

jQuery.when(loggedIn, databaseReady).then(function() {
  //do something
});
于 2012-09-14T06:47:31.307 に答える
2

遅延オブジェクトを使用して、Webkitブラウザーで適切に機能する流動的なデザインを作成できます。Webkitブラウザーは、ウィンドウがサイズ変更されるピクセルごとにサイズ変更イベントを発生させます。FFやIEは、サイズ変更ごとに1回だけイベントを発生させます。その結果、ウィンドウのサイズ変更イベントにバインドされた関数が実行される順序を制御することはできません。このようなものが問題を解決します:

var resizeQueue = new $.Deferred(); //new is optional but it sure is descriptive
resizeQueue.resolve();

function resizeAlgorithm() {
//some resize code here
}

$(window).resize(function() {
    resizeQueue.done(resizeAlgorithm);
});

これにより、コードの実行がシリアル化され、意図したとおりに実行されます。オブジェクトメソッドを遅延へのコールバックとして渡すときの落とし穴に注意してください。このようなメソッドが遅延へのコールバックとして実行されると、「this」参照は遅延オブジェクトを参照して上書きされ、メソッドが属するオブジェクトを参照しなくなります。

于 2011-03-01T12:27:06.193 に答える
2

JQueryを利用するサードパーティライブラリと統合することもできます。

そのようなライブラリの1つがBackboneであり、これは実際には次のバージョンでDeferredをサポートする予定です。

于 2011-05-15T07:00:42.430 に答える
1

実際のコードでDeferredを使用しました。プロジェクトjQueryターミナルには、ユーザーが定義したコマンドを呼び出す関数execがあります(ユーザーがコマンドを入力してEnterキーを押すなど)。APIにDeferredsを追加し、配列を使用してexecを呼び出します。このような:

terminal.exec('command').then(function() {
   terminal.echo('command finished');
});

また

terminal.exec(['command 1', 'command 2', 'command 3']).then(function() {
   terminal.echo('all commands finished');
});

コマンドは非同期コードを実行でき、execはユーザーコードを順番に呼び出す必要があります。私の最初のAPIは、一時停止/再開呼び出しのペアを使用し、新しいAPIでは、ユーザーがpromiseを返すときにそれらを自動的に呼び出します。したがって、ユーザーコードは

return $.get('/some/url');

また

var d = new $.Deferred();
setTimeout(function() {
    d.resolve("Hello Deferred"); // resolve value will be echoed
}, 500);
return d.promise();

私は次のようなコードを使用します:

exec: function(command, silent, deferred) {
    var d;
    if ($.isArray(command)) {
        return $.when.apply($, $.map(command, function(command) {
            return self.exec(command, silent);
        }));
    }
    // both commands executed here (resume will call Term::exec)
    if (paused) {
        // delay command multiple time
        d = deferred || new $.Deferred();
        dalyed_commands.push([command, silent, d]);
        return d.promise();
    } else {
        // commands may return promise from user code
        // it will resolve exec promise when user promise
        // is resolved
        var ret = commands(command, silent, true, deferred);
        if (!ret) {
            if (deferred) {
                deferred.resolve(self);
                return deferred.promise();
            } else {
                d = new $.Deferred();
                ret = d.promise();
                ret.resolve();
            }
        }
        return ret;
    }
},

dalyed_commandsは、すべてのdalyed_commandsで再度execを呼び出すresume関数で使用されます。

およびコマンド機能の一部(関連のない部分を削除しました)

function commands(command, silent, exec, deferred) {

    var position = lines.length-1;
    // Call user interpreter function
    var result = interpreter.interpreter(command, self);
    // user code can return a promise
    if (result != undefined) {
        // new API - auto pause/resume when using promises
        self.pause();
        return $.when(result).then(function(result) {
            // don't echo result if user echo something
            if (result && position === lines.length-1) {
                display_object(result);
            }
            // resolve promise from exec. This will fire
            // code if used terminal::exec('command').then
            if (deferred) {
                deferred.resolve();
            }
            self.resume();
        });
    }
    // this is old API
    // if command call pause - wait until resume
    if (paused) {
        self.bind('resume.command', function() {
            // exec with resume/pause in user code
            if (deferred) {
                deferred.resolve();
            }
            self.unbind('resume.command');
        });
    } else {
        // this should not happen
        if (deferred) {
            deferred.resolve();
        }
    }
}
于 2014-06-02T07:34:17.557 に答える
1

ehyndsによる回答は、応答データをキャッシュするため、機能しません。PromiseでもあるjqXHRをキャッシュする必要があります。正しいコードは次のとおりです。

var cache = {};

function getData( val ){

    // return either the cached value or an
    // jqXHR object (which contains a promise)
    return cache[ val ] || $.ajax('/foo/', {
        data: { value: val },
        dataType: 'json',
        success: function(data, textStatus, jqXHR){
            cache[ val ] = jqXHR;
        }
    });
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retreived using an
    // XHR request.
});

Julian D.による回答は正しく機能し、より良い解決策です。

于 2015-01-28T07:44:50.793 に答える