1

Deferrentと、この特定のケースでの使用方法に関する問題に直面しています。

シナリオは次のとおりです。

サーバーにデータを送信するループがあります。例えば:

var array = [{"effect":"save","params":["login_0_form_form_login"],"url":"http://www.example.local/login"},{"effect":"redirect","params":["index"],"url":"http://www.example.local/index"}];

$.each(array,function(key,payload) {

 $.post(payload.url,payload);

});

次に、ajax呼び出しの結果を処理するsuccessメソッド。

App.success = function(result){
   //Here I am deciding what to do with the result and checking for errors or warnings

   if(result.notification.success) {
      //Everything is good
   }
   else if(result.notification.error) {
      //Something is wrong, somehow stop the other ajax call  
   }
}

それにもかかわらず、私が直面している問題は、サーバーがエラー(たとえば、不正なログインデータ)を返す可能性があることです。このシナリオでは、サーバーから不正なログインデータが返されますが、リダイレクトされます。前のリクエストがエラーを返したかどうかをどうにかして制御する必要があります。はいの場合は、投稿を続けないでください。

$ .when関数内で、$。thenを使用して、$。postを返そうとしました。しかし、私は自分が望んでいたことを達成できませんでした。

4

1 に答える 1

2

ループを使用しないでください。AJAX 呼び出しは、一度に 1 つずつ実行するのではなく、すぐに (並行して) 開始します。

再帰的なコールバック ループを使用して各アクションを順番に処理し、別のオブジェクトと組み合わせて$.Deferred何が起こったかを通知できるようにします。

function processActions(actions) {
    var def = $.Deferred();

    (function nextAction() {
        var action = actions.shift();  // dequeue the next action
        if (action) {
            $.ajax(...).done(nextAction).fail(function() {
                def.reject();  // there was an error
            });
        } else {
            def.resolve();     // all done
        }
    })();  // invoke this function immediately

    return def.promise();
}
于 2012-10-18T09:39:52.070 に答える