SOURCE

/**
 * 
 */
fetch('http://xxxx').then(response=> response.json()).then(data=> console.log(data)).catch(error=>console.log('错误',error))
//使用async/await
async function getData() {
  try {
    const response = await fetch('https://xxxx');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('错误:', error);
  }
}


//为什么要用Fetch?
//1.更简洁的语法
// XHR:需要多行配置和回调
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => { /* ... */ };
xhr.send();

// Fetch:一行发起请求
fetch(url).then(r => r.json()).then(data => { /* ... */ });

//2. 原生Promise支持
/*避免回调地狱
支持async/await
更好的错误处理链
*/

//Fetch解决了XHR的哪些问题?
1. 回调地狱问题
// XHR:嵌套回调
xhr1.onload = function() {
  xhr2.onload = function() {
    xhr3.onload = function() {
      // 回调地狱
    };
  };
};

// Fetch:Promise链式调用
fetch(url1)
  .then(r => r.json())
  .then(data => fetch(url2))
  .then(r => r.json())
  .then(data => fetch(url3))
  .catch(error => console.error(error));
  2. 状态判断复杂
  // XHR:需要判断readyState和status
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // 成功处理
  }
};

// Fetch:response.ok直接判断
fetch(url).then(response => {
  if (response.ok) {
    // 成功处理
  }
});
3. 错误处理不统一
// XHR:需要多个事件监听
xhr.onerror = handleNetworkError;
xhr.ontimeout = handleTimeout;
xhr.onabort = handleAbort;

// Fetch:统一catch处理
fetch(url).catch(error => {
  // 统一错误处理
});

//------------XHR功能在Fetch中的实现
1.超时控制
// XHR方式
xhr.timeout = 5000;
xhr.ontimeout = () => console.log('超时');

// Fetch方式(手动实现,使用AbortController + setTimeout)
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);//5s后取消请求

fetch(url, { signal: controller.signal })
  .then(response => {
    clearTimeout(timeoutId);
    return response.json();
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('请求超时');
    }
  });
console 命令行工具 X clear

                    
>
console