我想向API发出GET请求并从中检索数据。据我所知,我的$.getJSON
是异步的,这意味着它不会等到它完成之后再继续执行我的代码。现在,我认为研究可以告诉我的最佳途径是使用回调,但是我仍然对如何最好地实现这一点感到困惑(即使是最好的方法)。您可以使用下面的示例代码进行演示吗?
function getData(URL) {
$.getJSON(URL, function(data) {
//play with data, such as save to localStorage on web broswer
}
}
function container() {
var URL = "https://someurl....";
getData(URL);
// Now access the data from localStorage, which was saved during .getJSON function, will fail if getData is ran async due to delay
// Open URL here appending data from the GET request, have to obviously have it prior to proceeding
}
我知道我们对此进行了广泛讨论,并且向您保证,在进行研究之前,我不会发布此问题,但是我仍然很难。如果有人可以用这个例子来演示,那可能真的可以帮助我理解。谢谢!
答案 0 :(得分:-1)
您可以让getData
使用回调函数:
function getData(URL, cb) {
$.getJSON(URL, function(data) {
//play with data, such as save to localStorage on web broswer
cb(data);
}
}
function container() {
var URL = "https://someurl....";
getData(URL, function(data) {
// Now access the data from localStorage
});
}
或返回一个Promise,然后允许您使用async / await。
function getData(URL) {
return new Promise(function(resolve, reject) {
$.getJSON(URL, function(data) {
//play with data, such as save to localStorage on web broswer
resolve(data);
}
});
}
async function container() {
var URL = "https://someurl....";
var data = await getData(URL);
// Now access the data from localStorage
}
由于$.getJSON
已经返回了诺言,所以更好:
function getData(URL) {
return $.getJSON(URL).then(function(data) {
//play with data, such as save to localStorage on web broswer
return data;
});
}
// container function stays the same as above
或者:
async function getData(URL) {
var data = await $.getJSON(URL);
//play with data, such as save to localStorage on web broswer
return data;
}
// container function stays the same as above