这是一个没有使用回调的包的答案
创建一个递归处理所有东西的函数。
getArray(stuffs, callback, index = 0, array = []) {
// Did we treat all stuffs?
if (stuffs.length >= index) {
return callback(array);
}
// Treat one stuff
if (condition) {
array.add(stuffs[index]);
// Call next
return getArray(stuffs, callback, index + 1, array);
}
// Get a stuff asynchronously
return api.compute(stuffs[index], (resp) => {
array.add(resp.stuff);
// Call next
return getArray(stuffs, callback, index + 1, array);
});
}
怎么称呼?
getArray(stuffs, (array) => {
// Here you have your array
// ...
});
编辑:更多解释
我们想要将您的循环转换为处理异步函数调用的循环。
目的是一个getArray 调用将处理您的stuffs 数组的一个索引。
处理完一个索引后,函数会再次调用自己来处理下一个索引,直到全部处理完毕。
-> Treat index 0 -> Treat index 1 -> Treat index 2 -> Return all result
我们正在使用参数通过流程传递信息。 Index 知道我们必须处理哪个数组部分,array 保留我们计算过的部分。
编辑:改进 100% 异步解决方案
我们在这里所做的是将您的初始 for 循环简单地转换为异步代码。可以通过使其完全异步来改进它,这使它变得更好但稍微困难一些。
例如:
// Where we store the results
const array = [];
const calculationIsDone = (array) => {
// Here our calculation is done
// ---
};
// Function that's gonna aggregate the results coming asynchronously
// When we did gather all results, we call a function
const gatherCalculResult = (newResult) => {
array.push(newResult);
if (array.length === stuffs.length) {
callback(array);
}
};
// Function that makes the calculation for one stuff
const makeCalculation = (oneStuff) => {
if (condition) {
return gatherCalculResult(oneStuff);
}
// Get a stuff asynchronously
return api.compute(oneStuff, (resp) => {
gatherCalculResult(resp.stuff);
});
};
// We trigger all calculation
stuffs.forEach(x => x.makeCalculation(x));