多个顺序的fetch()承诺

弗朗切斯科

我必须做一个序列的fetch()承诺:一次我只有1个网址,这意味着只有1个fetch()诺言。每次我收到一个json时,它都会包含另一个json的网址,因此我必须做出另一个fetch()承诺。

我可以使用多个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);
来宾271314

您可以使用递归

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)
})

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章