【问题标题】:Dynamically call getJSON inside $.when block在 $.when 块中动态调用 getJSON
【发布时间】:2021-06-07 08:02:35
【问题描述】:

有没有办法用更少的代码行重写它,通过使其动态而不是使用不同的索引进行多次类似的调用?

var input = getInput();
var URL = getEndpointURL();
var results = [];
        $.when(
            $.getJSON(URL+input[0], function (data,status) {
                results[0] = data;
            }),
            $.getJSON(URL+input[1], function (data,status) {
                results[1] = data;
            }),
            $.getJSON(URL+input[2], function (data,status) {
                results[2] = data;
            }),
            $.getJSON(URL+input[3], function (data,status) {
                results[3] = data;
            }),
            $.getJSON(URL+input[4], function (data,status) {
                results[4] = data;
            }),
        ).then(function() {
            processResults(results);
        });

【问题讨论】:

  • 如果可能的话,我建议您通过更改端点以在单个请求中接收所有数据来避免减少 JS 代码(和同时请求)数量的问题。这将大大减少网络流量并使服务器性能更好。

标签: javascript jquery asynchronous getjson .when


【解决方案1】:

假设input 是一个数组,您可以通过map() 数组来请求承诺并在该数组上使用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>

【讨论】:

    猜你喜欢
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多