多个,顺序 fetch() 承诺 [英] multiple, sequential fetch() Promise

查看:222
本文介绍了多个,顺序 fetch() 承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to make a sequence of fetch() Promise: I have only 1 url at a time, this means only 1 fetch() promise. Every time I receive a json,this one contains an url for another json, so I have to make another fetch() promise.

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

I'm able to work with multiple promise, but in this case I can't do Promise.all(), because I don't have all the url, but only one.

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

This example doesn't work, it all freezes.

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

这篇关于多个,顺序 fetch() 承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆