Javascript 获取 API 链 "then"

Javascript fetch API chain "then"

我是 JS 的新手,不知道如何进行以下工作:

我想 运行 在获取 API 的不同阶段发挥作用(出于测试原因 console)。当 fetch started because of click –> then when fetch received a response (text) -> then when the fetch response has been parsed -> and finally when the parsed response text has replaced the HTML of an existing DOM-element.

时喜欢 运行 控制台
var doFetch = (url) => {
  fetch(url, {
    method: "GET",
    headers: new Headers({
        'X-Requested-With': 'fetch'
    })
  }){
    console.log("fetch request started because of click on element");
  }
  .then(response => response.text();
    console.log("fetch request has received the response text");
  )
  .then(response => {
    let content = new DOMParser().parseFromString(text, "text/html");
    console.log("the received request response text was DOMparsed");
  })
  .then(response => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  }
};

欢迎提供有关如何更正代码的任何提示!

为了进行链接,您需要从每个 .then block 中 return。另外,您的第一个 console.log() post 提取函数的语法不正确

var doFetch = (url) => {

  fetch(url, {
    method: "GET",
    headers: 'X-Requested-With': 'fetch'
  })
  .then(response => {
     console.log("fetch request has received the response text");
     return response.text();

  })
  .then(response => {
    let content = new DOMParser().parseFromString(text, "text/html");
    console.log("the received request response text was DOMparsed");
    return content
  })
  .then(content => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  });
  console.log("fetch request started because of click on element"); // This will be executed first
};

每个 then 块将执行如果前面的 then 块 return。

您的第一个 console.log 语句应该在 doFetch 函数的开头。它不能写在你代码中当前写的地方。

您还应该在末尾链接一个 catch 块以捕获承诺链中可能发生的任何错误。

作为旁注,您应该使用 constlet 关键字来声明变量而不是 var.

const doFetch = (url) => {
  console.log("fetch request started because of click on element");

  fetch(url, {
    method: "GET",
    headers: 'X-Requested-With': 'fetch'
  })
  .then(response => {
    console.log("fetch request has received the response text");
    return response.text();
  })
  .then(response => {
    console.log("the received request response text was DOMparsed");
    return new DOMParser().parseFromString(text, "text/html");
  })
  .then(response => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  })
  .catch(error => console.log(error));
};