我花了很多天的时间尝试这里和其他论坛上的各种技术,但就是无法理解它。
我尝试过.map(),我尝试过全局变量,我尝试过我能想到的一切。 陡峭的学习曲线
我将一个长函数拆分为几个较小的函数,以使代码更具可读性和功能性,下面的代码由我用于映射的主函数调用,下面的代码的目的是去获取数据从模型(通过views.py)然后将其传递回主函数,它将是包含名称、城市、城镇、国家的数据,在我拆分长函数之前它工作得很好,但现在不会传递变量。
在我console.log“城镇中的对象”的地方,它在控制台中看起来不错,但是一旦超出该获取,我就丢失了,我尝试从获取函数mappointobject(我相信是一个对象数组)中返回数据,但是它不会,我试图在最终的 console.log 上放置一个“等待”,但什么也没有,似乎无论我尝试什么在结束获取函数括号后都会失败}),主函数只是对我说“未定义”
下面是我在获取右括号之前在 console.log 中得到的内容
城镇中的物体 (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
let mappointsobject;
async function radiocontacttownslist() {
fetch(`/conlogger/getradiocontactsdata`, { //this fetch command via views.py gets the data in the radiocontacts list
method: 'POST',
credentials : 'same-origin',
headers: {//'Accept': 'application/json', //Django needs these headers
'X-CSRFToken': getCookie("csrftoken"),
'Content-type': 'application/json' , //Indicates that the request body format is JSON.
'X-Requested-With': 'XMLHttpRequest'
},
})
.then(response => response.json())
//get the promise and when data comes back, take the response and convert and return as JSON
.then(result => {
console.log(result);
mappointsobject = JSON.parse(result) //convert from JSON to javascript object - also see next line
console.log('the objects the towns',mappointsobject) // this is all the objects and all the data from the radio contacts table
}) //end of fetch brackets
console.log('townlisttestoutsideoffetch',mappointsobject)
return mappointsobject;
}
我尝试过全局变量,我尝试过 .map() (完全失败了,但给了它一个裂缝),我尝试过将字符串和数字传回,它们很好地传回主函数,但它没有不喜欢该数组或存在时序冲突。我还尝试在主函数和此函数的各个点使用“等待”,但似乎无法合理化它。
寻求指导,我还在学习,还有很多东西要学,谢谢
您遇到的问题可能是由于 JavaScript 的异步行为造成的。
fetch
函数异步工作,这意味着它返回一个在获取数据时解析的承诺。但是,在获取数据之前,会立即执行 console.log
块外部的 .then
,从而得出 undefined
值。
这里有一种使用
async/await
修复它的方法,它可以使异步代码更易于使用:
async function radiocontacttownslist() {
try {
const response = await fetch(`/conlogger/getradiocontactsdata`, {
method: 'POST',
credentials : 'same-origin',
headers: {
'X-CSRFToken': getCookie("csrftoken"),
'Content-type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
const result = await response.json(); // Await the response and parse it as JSON
const mappointsobject = JSON.parse(result); // Assuming the result is a stringified JSON object
console.log('the objects the towns', mappointsobject); // Now you can log it
return mappointsobject; // Return the value
} catch (error) {
console.error("Error fetching data:", error); // Handle any errors
return null; // Return null or handle the error as needed
}
}
// Call the function and handle the result
(async () => {
const townsList = await radiocontacttownslist();
console.log('townlisttestoutsideoffetch', townsList); // This will now log after the fetch is done
})();
async/await
: 这允许代码等待 fetch
完成后再继续。try/catch
以捕获提取期间可能发生的任何错误。现在,当你调用
radiocontacttownslist
时,它会返回获取到的数据,并且fetch之外的console.log将可以访问到获取到的数据。