异步/等待连续的提取调用:如何?

问题描述 投票:0回答:1

举个例子,假设我想构建一个动态 HTML 页面,显示太阳系所有行星和卫星的属性,从观测服务器 API 加载数据。

我执行 GET 请求来获取包含太阳系所有行星的 json。 然后,我需要循环每个行星来编写 HTML 页面,但我需要执行 GET 请求来获取另一个包含给定行星的所有卫星的 json 对象。

所以,我的代码如下所示:

    async function GetPlanets(Star) {
        const response = await fetch('https://observatory.app/api/planets?name=${Star}');
        var data = await response.json();
        showPlanets(data);  // This function writes the innerhtml of a table, 
    }
         
    async function GetMoons(Planet) {
        const response = await fetch('https://observatory.app/api/moons?name=${Planet}');
        var data = await response.json();
        return showMoons(data);  // This function writes the innerhtml of a table
    }
         
    function showPlanets(data) {
        let tab =
          `<thead><tr>
           <th>name     </th>
           <th>mass     </th>
           <th>gravity  </th>
           <th>moons    </th>
           </tr></thead>
          `;
        // Loop to access all the planets
        tab += `<tbody>`;
        for (let r of data.all_planets) {
            tab += `<tr>
            <td rowspan=2> ${r.name         }</td>
            <td> ${r.mass                   }</td>
            <td> ${(r.gravity).toFixed(2)   }</td>
            </tr>`;
            
            // Now add the moons
            tab += `<tr><td id="moons" colspan=3>`
            tab += GetMoons(r.name); // GET the moons of this planet
            tab += `</td></tr>`;
        }
        tab += `</tbody>`;
        // Setting innerHTML as tab variable
        document.getElementById("systemPlanets").innerHTML = tab;
    }
         
    function showMoons(data) {
        let tab =
          `<table><thead><tr>
           <th>name     </th>
           <th>mass     </th>
           <th>gravity  </th>
           </tr></thead>
          `;
        // Loop to access all the moons
        tab += `<tbody>`;
        for (let r of data.all_moons) {
            tab += `<tr>
            <td> ${r.name                   }</td>
            <td> ${r.mass                   }</td>
            <td> ${(r.gravity).toFixed(2)   }</td>
            </tr>`;
        }
        tab += `</tbody></table>`;
        return tab;
    }

<body>
部分的末尾有对
getPLanets(Sol);
的调用,然后页面应该显示数据。

现在,我看到所有请求都收到了答案,但我的页面没有构建。我短暂地看到了行星表,然后它只显示“未定义”。

在寻找解决方案时,我了解到异步函数无法返回值,而且我认为我已经理解异步函数不应该以我的方式调用,但实际上我对 Promise 和 async/await 一无所知,所以我正在努力寻找我应该做什么。 据我了解,我不想并行处理所有请求,而是只想一次处理每个行星/月球......

如何在第一个请求之后执行所有 GET 请求并将数据写入页面?

javascript asynchronous async-await
1个回答
0
投票

您没有等待致电

GetMoons

tab += GetMoons(r.name);

等待:

tab += await GetMoons(r.name);

这意味着执行此操作的函数需要是

async
:

async function showPlanets(data) {

也可以等待:

await showPlanets(data);
© www.soinside.com 2019 - 2024. All rights reserved.