Fetch API 是 Web 开发中用于网络请求的一个现代接口。它基于 Promise,可以让我们以异步方式发起网络请求。

特点

  • 基于 Promise:这使得异步处理更加直观和易于管理。
  • 易于使用:使用方式简单,与 XMLHttpRequest 类似,但提供了更多功能和更好的错误处理。
  • 返回值是 Promise:这使得链式调用成为可能,可以轻松地进行链式请求。

示例

fetch('/zh-cn/docs/Web/API/Fetch_API')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

资源

想要了解更多关于 Fetch API 的信息,可以参考以下链接:

Fetch API 示例