问题描述
我在JavaScript的字符串数组。数组的定义是这样的:
I have an array of strings in JavaScript. The array is defined like the following:
var myArray = [];
myArray.push('1');
myArray.push('2');
myArray.push('3');
我需要遍历数组,并调用运行异步函数。这个函数是这样的:
I need to loop through the array and call a function that runs asynchronously. That function looks like this:
function myAsyncFunction(id, callback) {
$.ajax({
url: '/api/items',
data: { 'id':id },
type: 'POST',
dataType: 'text',
success: function(result) {
if (callback) {
callback();
}
}, error: function() {
if (callback) {
callback();
}
}
}
我想通过所有的项目在我的数组进行迭代,并计算出它需要多长时间来运行所有的人。我想要做这样的事情:
I'm trying to iterate through all of the items in my array and figure out how long it takes to run all of them. I want to do something like this:
var startTime = new Date();
for (var i=0; i<myArray.length; i++) {
myAsyncFunction(myArray[i]);
}
var duration = new Date() - startTime;
显然,上述不起作用,因为它不等待Ajax调用移动到下一个项目在数组中前完成。我知道我需要使用回调。但是,我不知道如何构建我的code的方式。我该怎么做呢?
Obviously, the above does not work because it does not wait for the ajax call to finish before moving to the next item in the array. I know I need to use callbacks. However, I'm not sure how to structure my code that way. How do I do this?
推荐答案
使用无极做这样的事情:
Use Promise and do something like this:
var myArray = [1, 2, 3];
var promises = [];
var startTime = new Date();
var duration;
for (var i = 0, len = myArray.length; i < len; i++) {
var def = $.Deferred();
promises.push(def);
(function(i) {
$.ajax({
url: '/api/items',
data: { 'id':myArray[i] },
type: 'POST',
dataType: 'text'
}).done(function() {
promises[i].resolve();
});
})(i);
}
$.when.apply($, promises).done(function() {
duration = new Date() - startTime;
console.log(duration);
});
我没有测试过,但我认为它可以与一些适应:)结果运行良好
我认为,随着计数器的解决方案可能在一定条件下会失败。
I have not tested, but I think it can work well with some adaption :)
I think that the solution with the counter may fail under certain conditions.
编辑:它的工作原理
这篇关于与异步的JavaScript函数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!