我想编写一个从API请求某些信息的应用程序。只要此信息不可用,我就不想继续其余的应用程序。我已经尝试过了:
function suggestion(callback) {
xhr.open('GET', 'http://localhost:3001/');
xhr.onload = function() {
var a = JSON.parse(xhr.responseText);
console.log(a);
callback(a);
};
xhr.send();
}
var sugg = suggestion(function(lista) {
var s = [];
lista.forEach(element => {
s.push(element.event);
});
console.log(s);
return s;
});
为什么ugg返回未定义?
答案 0 :(得分:2)
只要此信息不可用,我就不想继续其余的应用程序
这不是您使用Web技术(如果使用React的话,即使它是React本机的)也要使用的技术。相反,您可以让应用程序在未完成异步操作时显示适当的“正在加载”或“待处理”状态,然后在操作完成时更新该状态。
为什么ugg返回未定义?
sugg
为undefined
,因为suggestion
没有返回值。调用永不return something
的函数的结果始终是undefined
。您的回调具有return
的事实并不重要,没有任何东西使用callback()
在suggestion
中返回的内容(即使这样做,也可以做到) 以后,而不是分配给sugg
时)。
因此,将这两部分信息放在一起,我们得到:
function suggestion(callback){
// (You probably need something declaring `xhr` and assigning
// `new XMLHttpRequest()` to it here)
xhr.open('GET', 'http://localhost:3001/');
xhr.onload = function() {
var a = JSON.parse(xhr.responseText);
console.log(a);
callback(a);
};
xhr.send();
}
showPendingState(); // ***
suggestion(function(lista){
var s = [];
lista.forEach(element => {
s.push(element.event);
});
console.log(s);
showRealStateUsing(s); // ***
});
但是,我建议使用promise而不是原始回调,并处理错误情况。而且,如果我们要兑现承诺,我们可以使用现代的fetch
而不是旧的XHR:
function suggestion() {
return fetch('http://localhost:3001/')
.then(response => {
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
return response.json();
});
}
showPendingState();
suggestion()
.then(showRealStateUsing) // `showRealStateUsing` receives the suggestion as an argument
.catch(showErrorState); // `showErrorState` receives the error as an argument
如果您要针对的是支持async
functions(和/或转码)的环境,我们可以简化一下:
async function suggestion() {
const response = await fetch('http://localhost:3001/');
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
return response.json();
}
// (in an `async` function)
showPendingState();
try {
showRealStateUsing(await suggestion());
} catch (error) {
showErrorState(error);
}