【发布时间】:2018-11-29 17:34:36
【问题描述】:
我有一个 userId 数组,我在 getOrdersByUserId() 中使用它来获取这些用户在特定月份下的订单:
function getOrdersByUserId(userId, month = 4) {
const apiService = new ApiService();
return apiService.getOrdersList(`?OrderingUser=${userId}`)
.then(orders => {
const monthOrders = orders.filter(order => new Date(order.FromTime)
.getMonth() === month);
return monthOrders;
});
}
这里是 ApiService 中的 getOrdersList():
getOrdersList(queryString = '') {
return httpsRequest.createRequest(this.URL.ordersList + queryString, {}, this.requestHeaders, 'GET')
.then(result => JSON.parse(result).Records);
}
httpsRequest.createRequest 返回一个通过 API 响应解决的承诺(如果需要,我也可以共享该代码)。
当我用我拥有的 8 个用户 ID 测试 getOrdersByUserId() 时,我每次都得到正确的记录。当我将这些调用放入 Promise 链并使用 Promise.All() 执行它们时,就会中断。我在这个答案的帮助下编写了以下代码:Wait for forEach with a promise inside to finish
const promises = userIds.map(userId => {
return getOrdersByUserId(userId, month)
.then(orders => {
return orders;
});
});
Promise.all(promises).then(results => {
console.log(results);
}).catch(err => {
console.log(err);
});
使用 8 个用户 ID 进行测试我得到了四五次这个错误:
(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected end of JSON input
经过大量控制台日志记录后,当 httpsRequest.createRequest() 给出的结果为空字符串而不是来自 API 的 JSON 响应时,似乎会发生此错误。那么为什么所有这些具有相同 userIds 的调用都单独工作,但在 Promise 链中执行时会中断?我该如何解决这个问题?
【问题讨论】:
标签: javascript ecmascript-6 promise