Javascript 为多个页面调用多个fetch调用的最佳方法?(同时等待/然后)

Javascript 为多个页面调用多个fetch调用的最佳方法?(同时等待/然后),javascript,promise,async-await,Javascript,Promise,Async Await,我正在尝试从这个星球大战API中获取所有角色,我对JS还相当陌生。我想知道最好的方法是什么。我想出了几个解决办法。第二种解决方案看起来很干净;然而,它有点硬编码,因为它排除了添加更多页面的可能性 谢谢你抽出时间 const characters = []; var url; async function getAllRequests(url) { const response = await fetch(url); const data = await response.jso

我正在尝试从这个星球大战API中获取所有角色,我对JS还相当陌生。我想知道最好的方法是什么。我想出了几个解决办法。第二种解决方案看起来很干净;然而,它有点硬编码,因为它排除了添加更多页面的可能性

谢谢你抽出时间

const characters = [];
var url;

async function getAllRequests(url) {
    const response = await fetch(url);
    const data = await response.json();
    url = data.next;
    characters.push(...data.results);
    if(url !== null) {
        return getAllRequests(url);
    }
}

function foo(index) {
    let url = 'https://swapi.dev/api/people/?page=1';
    getAllRequests(url);
}
在.then示例中,加载从我的gif中获取的数据需要几秒钟:第一个gif是我立即重新加载并检查输出,第二个是我在几秒钟后检查输出

在wait示例中,它似乎在继续执行剩余代码之前,实际上是在等待承诺完成:


那么,等待暂停执行和.then语法的区别是什么呢?

您的第二个示例肯定比第一个更有效,因为第一个示例是序列化HTTP请求,而第二个示例允许它们并行发生

但是,如果有可能添加其他页面,并且这只能通过响应来确定,那么您的第一个示例可能是必要的


关于您的
await
/
示例,您的
await
版本与此等效:

function foo(index) {
    Promise.all(getAllRequests())
    .then(response => Promise.all(response.map(res => res.json())))
    .then(data => {
        data.forEach(object => characters.push(...object.results));
        console.log(characters);
    });
}

如果不在最终的
then()
中嵌套
console.log
,它将在创建
承诺后立即执行,而不是在它完成后执行。

async/await相当于预版本承诺。这只是es7中的一种新语法。第二种方法更具可读性,更易于理解。在性能方面没有任何区别。“第二种解决方案看起来很干净;但是,它有点硬编码,因为它排除了添加更多页面的可能性。”-是的,这就是问题所在。如果希望正确使用swapi提供的分页,那么需要使用第一种方法。
function foo(index) {
    Promise.all(getAllRequests())
    .then(response => Promise.all(response.map(res => res.json())))
    .then(data => data.forEach(object => characters.push(...object.results)));

    console.log(characters)
}
async function foo(index) {
    const responses = await Promise.all(getAllRequests());
    const data = await Promise.all(responses.map(res => res.json()));
    data.forEach(object => characters.push(...object.results));

    console.log(characters)
}
function foo(index) {
    Promise.all(getAllRequests())
    .then(response => Promise.all(response.map(res => res.json())))
    .then(data => {
        data.forEach(object => characters.push(...object.results));
        console.log(characters);
    });
}