I have a general question about how to write my app properly. I got my data from the server and then I want to start setting the objects preferably on the global scope if possible. How do I manage that without async: false (I read that it is a bad practice)? what is the correct way?
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);
}
});
}
Promises are the correct way to go (You should never pollute the global scope):
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',
});
}
With new es6 await syntax, you can even make this easier:
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',
});
}
Without knowing more, it's hard to tell you more. You can consider using a class:
// 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();
</div>