簡體   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