叮當(dāng)貓咪
2019-09-26 15:03:11
多個順序fetch()承諾我必須做一個fetch()承諾序列:一次我只有1個網(wǎng)址,這意味著只有1個fetch()諾言。每次我收到一個json時,它都會包含另一個json的網(wǎng)址,因此我必須做出另一個fetch()承諾。我可以使用多個promise,但是在這種情況下,我做不到Promise.all(),因為我沒有所有的URL,只有一個。這個例子不起作用,一切都凍結(jié)了。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貢獻(xiàn)1801條經(jīng)驗 獲得超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)})

開滿天機
TA貢獻(xiàn)1786條經(jīng)驗 獲得超13個贊
.catch()
應(yīng)該停止遞歸,除非fetchNextJson
在內(nèi)調(diào)用.catch()
。一種方法可以處理錯誤,然后返回fetchNextJson
在.then()
鏈接到.catch()
或.catch()
; 盡管目前的要求是fetchNextJson
使用當(dāng)前結(jié)果調(diào)用下一個,fetchNextJson
但似乎沒有其他要執(zhí)行的任務(wù)-除非從可選來源提供了url

阿晨1998
TA貢獻(xiàn)2037條經(jīng)驗 獲得超6個贊
“結(jié)論是不斷將then()添加到鏈中,直到最終返回非承諾?!?nbsp;從.then()
鏈到返回的任何結(jié)果fetchNextJson
應(yīng)在首次調(diào)用后得到保證。.then()
遞歸調(diào)用fetchNextJson
或返回累積結(jié)果或其他值作為承諾值
添加回答
舉報
0/150
提交
取消