【发布时间】:2018-01-15 01:12:46
【问题描述】:
我需要从 API 中读取数据,每个查询只提供 100 个结果,以及从何处获取下一个 100 个结果的时间戳。
我已经设法使用下面的代码一个接一个地执行多个请求,但由于某种原因,它永远不会返回到最初的承诺。它卡在“没有更多订单可取”上。
app.get('/test', (req, res) => {
const getOrders = (from) => {
return request(mcfApiUrl + "changes?created_after_ts="+from+"&key="+mcfKey)
.then(xml => convert.xmlDataToJSON(xml,{explicitArray:false,mergeAttrs:true}))
.then(orders => checkForMore(orders));
}
const checkForMore = (orders) => {
return new Promise((resolve, reject) => {
if (orders['Orders']['orders'] == 100){
getOrders(orders['Orders']['time_to']);
console.log("Fetched "+ orders['Orders']['orders']+" orders");
console.log("More orders available from: "+moment(orders['Orders']['time_to']*1000).format());
}
else {
console.log("Fetched "+ orders['Orders']['orders']+" orders");
console.log("No more orders to fetch");
resolve(orders);
}
});
};
var fromdate = 1483999200;
getOrders(fromdate)
.then(output => res.send("Done")) // It never gets here
.catch(err => console.log(err));
});
我错过了什么?
【问题讨论】:
-
寻找无限循环的 ajax 请求?
-
我建议使用事件发射器或可观察对象
-
@Hitmands: if 语句应该使它成为非无限的。
-
@MinusFour:我也对其他解决方案持开放态度。我只是认为我的解决方案会很简单(如果可行的话......)
-
您没有在
if()中解析...试试resolve( getOrders(orders['Orders']['time_to']))
标签: javascript node.js express promise