3

仕事で問題があります。サーバーに依存するインストールのセクションがあります。やりたいこと: ユーザーがサーバーを削除すると、インストール コレクションがループし、依存するすべてのインストールが削除されます。そのために、サーバーからの応答を待ってから「then」関数に進むと言われているjQueryの「when」関数を使用します。依存インストールが 1 つしかない場合は問題なく動作します。ただし、JSON 応答を受け取った直後に then 関数に移動するため、インストールが増えると問題が発生します。

問題は、「when」関数をすべてのサーバー応答を待機させるにはどうすればよいかということです。例えば。$.postJSON を介して 3 つの削除要求を送信し、3 つの応答すべてを取得したら先に進みたいと考えています。「いつ」でそれができない場合、それを実現するために何を使用すればよいですか? それが役立つ場合は、すべてのエンティティ コレクションを KnockoutJS で維持しています。ありがとう!

編集:私はそれを次のように持っています:

$.when(DeleteDependentInstallations())
.then (function() {
   ...
});

DeleteDependentInstallations は次のようになります (疑似コード):

Search the installations collection;
If installation.ID equals server.InstallationID
{
  Add to dependent installations collection;
}
Repeat until the whole collection is searched;

for (i = 0; i < dependentInstallations.length; i++)
{
  DeleteInstallation(dependentInstallations[i]);
}

DeleteInstallations は $.postJSON 関数を使用した単純な関数です。

問題は、最初の JSON 応答の直後に .then 関数が実行されることです。

4

1 に答える 1

1

DeleteDependentInstallations が JQuery deferredsの配列を返すようにする必要があると思います。$.whenを使用すると、複数の引数を渡して、それぞれを待機する必要があることを知らせることができます。

あなたがしていることの全体的な文脈はわかりませんが、次のようなことがうまくいくと思います:

function DeleteDependentInstallations() {
     var installations = getDependantInstallations();
     var promises = [];
     for (var i = 0; i < installations.length; i++) {
         var installation = installations[i];
         promises.push(DeleteInstallation(installation));
     }
     return promises;
}

function DeleteInstallation(installation) {
      //do whatever here, but return the result of $.ajaxPost
      return $.post('/foo', installation);
}

このメソッドを使用すると、返されたすべての promise が完了するまで待機する必要があります。

$.when.apply(null, DeleteDependentInstallations()).then(function() { alert('wee!'); });

.apply() は、配列を引数コレクションとして渡すことができるようにするためのものです。

EDIT:頭の中で「遅延」と約束を混同していました。Deferredは $.ajax 呼び出しが返すものであり、promiseは $.when() 関数が返すものです。

EDIT2: .then() の動作がニーズに合わない場合は、 .done()メソッドも参照してください。

于 2012-08-27T19:39:05.843 に答える