多个,顺序fetch()承诺

Fra*_*coN 3 javascript json promise angularjs es6-promise

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

我可以使用多个承诺,但在这种情况下我不能这样做Promise.all(),因为我没有所有网址,只有一个网址.

这个例子不起作用,它都冻结了.

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);
Run Code Online (Sandbox Code Playgroud)

gue*_*314 6

你可以使用递归

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)
})
Run Code Online (Sandbox Code Playgroud)

  • 使用计数器进行简化演示而不是使用新网址返回http://plnkr.co/edit/5boVimpYnoE1o41FXZGG?p=preview (2认同)