2014-05-13 19 views
0

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

回答

1

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/

0

我没有jQuery的经验,但你的回调看起来有点腥。

在纯JS我建议尝试的这个行当中的东西:

function yourMainFunction 
{ 

    function callbackHandler(result) 
    { 
     // Code that depends on on the result of the callback 
    } 

    getAjaxResults(callbackHandler); 

} 



function getAjaxResults(callbackHandler) 
{ 

// Create xmlHttpRequest Handler, etc. 
// Make your AJAX request 

xmlHttp.onreadystatechange = function() 
{ 
    if (xmlHttp.readyState == 4 && xmlHttp.status==200) 
    { 
     // Do stuff you want to do if the request was successful 
     // Define a variable with the value(s) you want to return to the main function 

     callbackHandler(yourReturnVariable); 
    } 
} 
} 
1

我建议你看看jQuery的递延对象和jQuery.Deferred()-method,而不是让自己的回调队列功能(因为你已经在使用jQuery)。

描述:返回与方法可链接的效用 对象到多个回调注册到回调 队列,调用回调队列,和继电器的成功或失败的状态的任何同步或异步函数的 一个构造函数。

相关问题