问题描述
有没有办法用更少的代码行重写它,通过使其动态化而不是使用不同的索引进行多次类似的调用?
var input = getinput();
var URL = getEndpointURL();
var results = [];
$.when(
$.getJSON(URL+input[0],function (data,status) {
results[0] = data;
}),$.getJSON(URL+input[1],status) {
results[1] = data;
}),$.getJSON(URL+input[2],status) {
results[2] = data;
}),$.getJSON(URL+input[3],status) {
results[3] = data;
}),$.getJSON(URL+input[4],status) {
results[4] = data;
}),).then(function() {
processResults(results);
});
解决方法
假设 input
是一个数组,您可以 map()
数组来请求 promise 并在该数组上使用 Promise.all()
。
const URL = 'https://jsonplaceholder.typicode.com/todos/',input = [3,5,6];
const requestPromises = input.map(function(inp) {
return $.getJSON(URL + inp);
});
Promise.all(requestPromises).then(processResults)
function processResults(data) {
console.log(data)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>