gpt4 book ai didi

javascript - 从ajax数据设置App

转载 作者:行者123 更新时间:2023-12-03 01:29:58 25 4
gpt4 key购买 nike

我有一个关于如何正确编写我的应用程序的一般性问题。我从服务器获取数据,然后我想开始设置对象如果可能的话,最好在全局范围内。在没有 async: false 的情况下如何管理(我读到这是一个不好的做法)?什么是正确的方法?

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);
}
});
}

最佳答案

Promise 是正确的方法(你永远不应该污染全局范围):

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',
});
}

如果不了解更多,就很难告诉你更多。您可以考虑使用类:

// 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();

关于javascript - 从ajax数据设置App,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com