gpt4 book ai didi

javascript - 仅在上一次交互完成后递增(回调)

转载 作者:行者123 更新时间:2023-12-02 17:24:19 25 4
gpt4 key购买 nike

我在使用 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做对可能有点棘手。你要做的就是把你的 promise 叠成一条链。例如:

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 还必须返回一个 Promise,但 $.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com