繁体   English   中英

有人可以尝试为我解释这段代码吗?

[英]can someone try to explain this code for me?

这是一个非常简单的回调 function 但我仍然无法改变我的想法,有人可以向我解释一下吗? ps 我刚开始学js

const getToDos = (one) => {
  const req = new XMLHttpRequest();
  req.addEventListener(`readystatechange`, () => {
    if (req.readyState === 4 && req.status === 200) {
      one(undefined, req.responseText);
    } else if (req.readyState === 4) {
      one(`couldnt fetch data`, undefined);
    }
  });
  req.open(`GET`, `https://jsonplaceholder.typicode.com/todos/`);
  req.send();
};
getToDos((err, data) => {
  if (err) {
    console.log(err);
  } else {
    console.log(data);
  }
});

也有人能告诉我 xmlhttprequest 和 get 方法有什么区别吗? 前端使用 xmlhttprequest 并在后端使用 get 方法?

//Defining getToDos function, it takes one argument, which is another function
const getToDos = (one) => {
  //Create a request
  const req = new XMLHttpRequest();
  //Add an event listener on the status of the request and gives code to execute when it happens
  req.addEventListener(`readystatechange`, () => {
    //if request is completed (4) and its status is good (200)
    if (req.readyState === 4 && req.status === 200) {
      //Call the callback function give undefined as error and req.responseText as data
      one(undefined, req.responseText);
    //if request is completed (4) and its status is good (!= 200)
    } else if (req.readyState === 4) {
      //Call the callback function give `couldnt fetch data` as error and undefined as data
      one(`couldnt fetch data`, undefined);
    }
  });
  //prepare request and give endpoint
  req.open(`GET`, `https://jsonplaceholder.typicode.com/todos/`);
  //send request
  req.send();
};

//execute getToDos function and give a function as parameter
getToDos((err, data) => {
  //if err is not undefined
  if (err) {
    //log error
    console.log(err);
  } else {
    //log data
    console.log(data);
  }
});

这种代码很旧。 相反,您应该:

let data = await fetch(`https://jsonplaceholder.typicode.com/todos/`, {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    },
  })
if(data.status == 200){
  let parsed = await data.json()
  console.log(parsed)
} else {
  console.log(data)
}

––––– 编辑:为 OP 添加了示例

const aFunction = (callback) => {
  const aRandomBoolean = Math.random() < 0.5
  if(aRandomBoolean){
    console.log('Boolean is true !')
    callback('first parameter', 'second parameter')
  } else {
    console.log('Boolean is false !')
    callback('parameter 1', 'parameter 2')
  }
}

aFunction((paramA, paramB)=>{
  console.log(paramA, paramB)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM