我在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);
}
});
}