我对javascript很陌生,试图弄清楚如何在发送到另一个函数的回调中将值添加到调用方数组中。
基本代码是:
var newArray = new Array();
var oldArray = new Array();
oldArray.push(1);
oldArray.push(2);
oldArray.push(3)
for (var value in oldArray) {
someclass.functionThatWillPerformAjax(oldArray[value], function() {
// I am trying to figure out how to pass newArray in this callback
// so that when we receive the response from AJAX request,
// the value returned from the response pushed to a newArray
}
}
// once all calls are done, I have my newArray populated with values returned from server
最佳答案
您可以这样做:
var newArray = new Array();
var oldArray = new Array();
oldArray.push(1);
oldArray.push(2);
oldArray.push(3);
var someclass.doAjax = function(element, callback) {
// perform ajax request
callback(AjaxRequestResult); // send the result of the ajax request in the callback function
};
oldArray.forEach(function (element) { // for each element in oldArray
someclass.doAjax(element, function(doAjaxResult) { // perform doAjax function
newArray.push(doAjaxResult); // push the callback's result into newArray
});
});
但是您必须知道,在这种情况下,您的请求可能不会以被调用的顺序返回。