我有一个关于如何正确编写我的应用程序的一般性问题。 我从服务器获取了数据,然后开始设置对象 如果可能,最好在全球范围内使用。 我如何在没有异步的情况下进行管理:错误(我读到这是一种不良做法)? 正确的方法是什么?
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);
}
});
}
答案 0 :(得分:1)
承诺是正确的做法(您绝不应该污染全局范围):
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 await语法,您甚至可以使此操作更容易:
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',
});
}
不了解更多信息,很难告诉您更多信息。您可以考虑使用一个类:
// Helper function for simulating an AJAX call
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
class Person {
constructor(name, lastName) {
this.name = name;
this.lastName = lastName;
}
async getChartData() {
console.log(`Making call to /api/myapp/data.json?${this.name}`);
await delay(2000);
return {some: 'a', sample: 'b', data: 'c'};
}
async getOtherData() {
console.log(`Making call to /api/myapp/otherData.json?${this.name}`);
await delay(3000);
return {more: 'x', data: 'y'};
}
}
const person = new Person('John', 'Doe');
// These do not block (Functionally almost identical to using Promise.all in an async function)
// person.getChartData().then(data => console.log('Data Returned: ', data));
// person.getOtherData().then(data => console.log('Data Returned: ', data));
async function main() {
// These will "block" (Not really blocking, just waiting before continuing with the rest)
console.log('== await each ==');
const data = await person.getChartData();
console.log(data);
const otherData = await person.getOtherData();
console.log(otherData);
console.log('== Run concurrently ==');
const [data2, otherData2] = await Promise.all([person.getChartData(), person.getOtherData()]);
console.log('All data returned', data2, otherData2);
}
// Call the main function (This does not block the main thread)
main();