Javascript 从ajax数据设置应用程序
我有一个关于如何正确编写我的应用程序的一般性问题。 我从服务器获取了数据,然后我想开始设置对象 如果可能,最好在全球范围内。 如果没有async:false,我该如何管理它呢?我读到这是一种糟糕的做法? 正确的方法是什么Javascript 从ajax数据设置应用程序,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有一个关于如何正确编写我的应用程序的一般性问题。 我从服务器获取了数据,然后我想开始设置对象 如果可能,最好在全球范围内。 如果没有async:false,我该如何管理它呢?我读到这是一种糟糕的做法? 正确的方法是什么 var people = { url: 'api/myapp/data.json' name: '', lastName: '', age: 0 } var someFuncWithLastName(){ //some use of the data
var people = {
url: 'api/myapp/data.json'
name: '',
lastName: '',
age: 0
}
var someFuncWithLastName(){
//some use of the data that I got from the server
//people.lastName suppose...after it got the correct data from the ajax res
}
//Get Data from server
var getData = function() {
$.ajax({
method: 'GET',
url: 'api/myapp/data.json',
success: function(res){
people = res
// res = { url:'api/myapp/data.json', name:'John', lastName:'Snow', age:34}
},
error: function (error) {
console.log(error);
}
});
}
承诺是正确的方式,你永远不应该污染全球范围:
function someFuncWithLastName (){
//some use of the data that I got from the server
//people.lastName suppose...
getDataForChart().then(data => {
console.log(data);
}
}
//Get Data from server
var getDataForChart = function() {
return $.ajax({
method: 'GET',
url: 'api/myapp/data.json',
});
}
使用新的es6 wait语法,您甚至可以简化此过程:
function someFuncWithLastName() {
//some use of the data that I got from the server
//people.lastName suppose...
const data = await getDataForChart();
console.log(data);
}
//Get Data from server
var getDataForChart = function() {
return $.ajax({
method: 'GET',
url: 'api/myapp/data.json',
});
}
如果不知道更多,就很难告诉你更多。可以考虑使用类:
//用于模拟AJAX调用的Helper函数
const delay=ms=>new Promiseresolve=>setTimeoutresolve,ms;
班主任{
constructorname,lastName{
this.name=名称;
this.lastName=lastName;
}
异步getChartData{
console.log `调用/api/myapp/data.json?${this.name}`;
等待2000年;
返回{some'a',sample'b',data'c'};
}
异步getOtherData{
log`Making call to/api/myapp/otherData.json?${this.name}`;
等待3000;
返回{more:'x',data:'y'};
}
}
const person=新人“约翰”、“多伊”;
//这些函数在功能上与在异步函数中使用Promise.all几乎不同
//person.getChartData.thendata=>console.log“返回的数据:”,数据;
//person.getOtherData.thendata=>console.log“返回的数据:”,数据;
异步函数主{
//这些将不会真正阻塞,只是在继续其他操作之前等待
console.log'==等待每个==';
const data=await person.getChartData;
控制台日志数据;
const otherData=await person.getOtherData;
console.logotherData;
console.log'==并发运行==';
const[data2,otherData2]=等待承诺.all[person.getChartData,person.getOtherData];
console.log'All data returned',data2,otherData2;
}
//调用main函数,这不会阻止主线程
主要的好啊首先感谢弗兰克兹。关于它的两个问题:1。等待-它不是在从服务器获取数据之前停止所有应用程序吗?2.承诺-因此,如果我有很多其他函数,实际上所有的应用程序函数和变量都依赖于该数据,那么所有函数都将使用wait/then?当您进行ajax调用时,wait之后的任何函数都不会运行,直到ajax调用完成。虽然这可能会导致应用程序停止,因为在代码完成之前,该语句之后的任何内容都不会执行,但它实际上并没有阻止浏览器用于在屏幕上实际渲染元素的主线程。您可以按顺序运行多个调用,而无需实际阻塞,如果您不等待它,您仍然可以使用它而无需实际阻塞任何内容。我将在课堂上澄清一点示例关于如何编写的一般问题,例如,某个应用程序在SO不属于主题。或者是一个更好的地方。