下面是一个简单的示例代码,用于展示如何使用JavaScript执行多个请求,每个请求的参数由上一个请求返回结果决定,将所有请求的结果保存到一个数组中,同时记录请求的次数和总体的请求时间。

let results = []; // 存储所有请求的结果
let count = 0; // 记录请求次数
let startTime = Date.now(); // 记录开始时间

function makeRequest(url) {
  return new Promise(function(resolve, reject) {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = function() {
      if (xhr.status === 200) {
        resolve(xhr.responseText);
      } else {
        reject(xhr.statusText);
      }
    };
    xhr.onerror = function() {
      reject('Network Error');
    };
    xhr.send();
  });
}

makeRequest('https://api.example.com/first')
  .then(function(response) {
    results.push(response);
    count++;
    return makeRequest('https://api.example.com/second/' + response);
  })
  .then(function(response) {
    results.push(response);
    count++;
    return makeRequest('https://api.example.com/third/' + response);
  })
  .then(function(response) {
    results.push(response);
    count++;
    let endTime = Date.now(); // 记录结束时间
    console.log('All requests completed in ' + (endTime - startTime) + 'ms.');
    console.log('Results:', results);
  })
  .catch(function(error) {
    console.error('Error:', error);
  });

在上面的示例代码中,我们定义了一个makeRequest()函数,它返回一个Promise对象,用于发送一个HTTP请求。然后我们使用makeRequest()函数执行了三个请求,每个请求的URL都是由上一个请求返回结果决定的。在每个请求的回调函数中,我们将结果保存到results数组中,并增加count计数器的值。

最后,在最后一个请求的回调函数中,我们记录了结束时间,并通过控制台输出了请求总时间和所有请求的结果。如果有任何请求失败,则会在catch块中处理错误。

请注意,这只是一个简单的示例代码,实际应用中可能需要进行更多的错误处理和数据验证。

javascript执行多个请求每个请求的参数由上一个请求返回结果决定全部请求的最后结果保存到一个数组中同时记录请求的次数和总体的请求时间

原文地址: http://www.cveoy.top/t/topic/g7E 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录