javascript - 如何访问和使用 do while 循环的返回值?

标签 javascript arrays return-value do-while

我正在尝试访问 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/

相关文章:

javascript - 在小部件中使用 mootools 库时的兼容性?

javascript - UI 未检测到可观察数组

c - 为什么这会在终止时给出(非零)错误代码?

c++ - 从 std::thread 获取返回码?

php - 方法返回状态 : bool, string, const... (PHP)

javascript - AngularFire,如何通过uid在页面上显示姓名/电子邮件?

javascript - 为 Angular $http 请求编写静态回退内容脚本

javascript - 未捕获的 TypeError : lineChart. Line 不是 Chart.js 中的函数

python - 在 python 中获取子字符串的更快方法?

python - 如何在不将音频文件保存在磁盘上的情况下将 numpy 数组转换为字节对象?