亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

多個順序fetch()承諾

多個順序fetch()承諾

叮當貓咪 2019-09-26 15:03:11
多個順序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);
查看完整描述

3 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

您可以使用遞歸

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


查看完整回答
反對 回復 2019-09-26
?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

.catch()應該停止遞歸,除非fetchNextJson在內調用.catch()。一種方法可以處理錯誤,然后返回fetchNextJson.then()鏈接到.catch().catch(); 盡管目前的要求是fetchNextJson使用當前結果調用下一個,fetchNextJson但似乎沒有其他要執行的任務-除非從可選來源提供了url

查看完整回答
反對 回復 2019-09-26
?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

“結論是不斷將then()添加到鏈中,直到最終返回非承諾?!?nbsp;.then()鏈到返回的任何結果fetchNextJson應在首次調用后得到保證。.then()遞歸調用fetchNextJson或返回累積結果或其他值作為承諾值 

查看完整回答
反對 回復 2019-09-26
  • 3 回答
  • 0 關注
  • 1119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號