【发布时间】:2016-10-28 07:45:35
【问题描述】:
我必须创建一系列fetch() Promise:我一次只有一个 url,这意味着只有 1 个fetch() promise。每次我收到一个json,这个包含另一个json的url,所以我必须再做一个fetch()promise。
我可以处理多个 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);
【问题讨论】:
-
预期行为和总体目标是什么?
-
预计将处理多少个请求?
$q.when()似乎没有必要。为什么在getItems()通话中在.then()之外拨打getItems(next_json_url)? -
基本情况是什么?什么时候停止获取数据?
-
我必须一次下载 1 个 json:第一个有下一个的参考,依此类推@guest27131,我想要多少就多少.. 1-40。当当前 json 中没有更多参考时,我将停止下一个 json
-
可能会考虑确保您有一个主导航地图并使用它来工作。会更容易处理错误,因为一个错误会破坏您的链条,而地图将为您提供一个跟踪更新的地方
标签: javascript angularjs json promise es6-promise