我在javascript中遇到回调函数问题。我想做的是:在for上循环并调用传递i作为参数的函数。考虑到这一点,我仅在上一个交互完成后才循环到下一个交互。我不知道这是否有问题,但是在我将i作为参数发送的函数中,我还有另一个回调函数。这是我的代码:

for(i=0; i<10; i++) {
    aux(i, function(success) {
        /*
         *  this should be made interaction by interaction
         *  but what happens is: while I'm still running my first interaction
         *  (i=0), the code loops for i=1, i=2, etc. before the response of
         *  the previous interaction
         */
        if(!success)
            doSomething();
        else
            doSomethingElse();
    });
}

function aux(i, success) {
    ... //here I make my logic with "i" sent as parameter
    getReturnFromAjax(function(response) {
        if(response)
            return success(true);
        else
            return success(false);
    });
});

function getReturnFromAjax(callback) {
    ...
    $.ajax({
        url: myUrl,
        type: "POST",
        success: function (response) {
        return callback(response);
    }
});
}

最佳答案

jQuery's Deferred可能有点棘手。您要做的就是将您的诺言链式地堆叠起来。例如:

var
  // create a deferred object
  dfd = $.Deferred(),

  // get the promise
  promise = dfd.promise(),

  // the loop variable
  i
;

for(i = 0; i < 10; i += 1) {
  // use `then` and use the new promise for next itteration
  promise = promise.then(
    // prepare the function to be called, but don't execute it!
    // (see docs for .bind)
    aux.bind(null, i, function(success) {
      success ? doSomethingElse() : doSomething();
    })
  );
}

// resolve the deferred object
dfd.resolve();


为了使它起作用,aux还必须返回一个诺言,但是$.ajax已经做到了,因此只需传递它,一切都应该起作用:

aux中:

function aux(i, callback) {
  console.log('executing for `aux` with', i);

  // return the ajax-promise
  return getReturnFromAjax(function(response) {
    callback(Boolean(response));
  });
}


getReturnFromAjax中:

function getReturnFromAjax(callback) {
  // return the ajax-promise
  return $.ajax({
    url: '%your-url%',
    type: '%method%',
    success: function (response) {
      callback(response);
    }
  });
}


演示:http://jsbin.com/pilebofi/2/

关于javascript - 仅在上一次交互完成后才增加(回调),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23630683/

10-12 07:22
查看更多