JavaScript提取API链“然后”

问题描述 投票:0回答:1

我是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");
  }
};

很高兴欢迎您提供任何有关纠正代码的提示!

javascript fetch httpresponse
1个回答
0
投票

为了进行链接,您需要从每个.then block中返回

var 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 => {
    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");
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.