我正在尝试访问 do while 循环的返回数据,但我无法这样做。
我已将信息存储在一个新变量 (starships) 中,然后返回此变量,但它说 starships 未定义。我发现这可能是范围界定问题,我该如何解决?
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
let starships = allResults;
return starships;
}
console.log(starships);
最佳答案
您需要获取从 getData
返回的值。使用您拥有的 async/await
结构执行此操作的最明显方法是仅await
它:
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
let starships = allResults;
return starships;
}
async function doTheDo() {
const test = await getData();
console.dir(test);
}
doTheDo();
关于javascript - 如何访问和使用 do while 循环的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57274143/