我正在尝试通过我的 API 端点获取数据,并希望用数据填充我的页面。我知道我必须使用 async/await 来确保变量已被填充。因此我写了以下几行,并想知道是否可以在异步函数中编写异步函数。它正在工作,但我不确定它是否是正确的方法:
async function getRoom(id) {
const response = await fetch('/api/zimmer/' + id);
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
throw new Error(message);
}
const rooms = await response.json();
console.log(rooms);
return rooms;
}
async function getSelectedItem() {
var e = document.getElementById("Objekt");
if (e.value > 0) {
zimmer_select.disabled = false;
var response = await getRoom(e.value);
console.log(response);
response.forEach(function(element) {
console.log(element);
});
} else {
zimmer_select.disabled = true;
}
console.log(e.value);
}
我认为实际上以这种方式使用它很好。如果您考虑一下,有时您必须在异步中使用异步。如果您有一些异步函数来获取数据,并且您必须遍历该数据并等待某些东西怎么办。如果你用 for each 循环它,你将无法使用 await,所以你应该把 async 放在它前面。所以只要它是干净的并且没有其他方法,我认为在 async 中使用 async 就可以了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句