javascript - 多个顺序的 fetch() Promise

标签 javascript angularjs json promise es6-promise

我必须制作一系列 fetch() Promise:我一次只有 1 个 url,这意味着只有 1 个 fetch() promise。每次我收到一个 json,这个包含另一个 json 的 url,所以我必须做出另一个 fetch() promise 。

我可以使用多个 promise,但在这种情况下我不能执行 Promise.all(),因为我没有所有的 url,只有一个。

这个例子不行,全卡死了。

function fetchNextJson(json_url) 
{
    return fetch(json_url, {
            method: 'get'
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(json) {
            console.log(json);
            return json;
        })
        .catch(function(err) {
            console.log('error: ' + error);
        });
}


function getItems(next_json_url) 
{
    if (!(next_json_url)) return;

    get_items = fetchNextJson(next_json_url);

    interval = $q.when(get_items).then(function(response) {
        console.log(response);
        next_json_url = response.Pagination.NextPage.Href;
    });

    getItems(next_json_url);
}


var next_json_url = 'http://localhost:3000/one';

getItems(next_json_url);

最佳答案

你可以使用递归

function fetchNextJson(json_url) {
    return fetch(json_url, {
            method: 'get'
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(json) {
            results.push(json);
            return json.Pagination.NextPage.Href 
                   ? fetchNextJson(json.Pagination.NextPage.Href)
                   : results
        })
        .catch(function(err) {
            console.log('error: ' + error);
        });
}


var next_json_url = 'http://localhost:3000/one';
var results = [];

fetchNextJson(json_url).then(function(res) {
  console.log(res)
})

关于javascript - 多个顺序的 fetch() Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38034574/

相关文章:

Angularjs 模板 : How to conditionally wrap a tag in another tag

javascript - 错误 : <path> attribute d: Expected number, "….43564672524005LNaN,NaNZ"

ruby-on-rails - 在 Rails 3 中翻译 JSON

Javascript:如何初始化二维数组

javascript - 如何在固定的时间内使用javascript函数?

javascript - 如何创建具有 getter 和 setter 方法的 Angular 工厂而不遇到竞争条件

java - 从java中的json数组中拆分json对象

javascript - 是否有一种非天真的方法来计算 DOM 偏移量的逻辑偏移量?

javascript - 独特的数组。扫雷 JavaScript

javascript - 使用 Karma + Jasmine 对 Browserify 项目进行单元测试