【发布时间】:2020-12-30 17:01:24
【问题描述】:
我正在尝试使用 promise 进行分页。这是我的工作流程。
第 1 步:分页总页数为 50。网址将类似于 url?page=1
第 2 步:在每个页面中,我将获得 50 个产品,我需要调用单独的 api。
唯一的条件是,在分页期间,只有在第一页的 50 api 调用完成时才应该调用第二页。获取所有 50 个页面后,它应该返回承诺。
到目前为止我所拥有的是。
let promises = [];
paginate(50);
Promise.all(promises)
.catch(function(err) {
console.log('err',err);
})
.then(() => {
console.log('All Done!!!!!');
});
function paginate(loop){
promises.push(
axios(config)
.then(function (response) {
// Got 50 products
})
.catch(function (error) {
console.log('err',err);
})
)
在Got 50 products 的地方,我仍然需要迭代 axios 中的 50 个产品。我不确定是否可以在 promise 中做 promise。
由于服务器无法承受突然的负载,唯一的条件是在第一个(或前50个api被调用)之后迭代第二个50个产品(或下一页的产品)。
编辑:
// 这里我有 50 个产品 正如我所说,在每个页面上我将获得 50 种产品,我将为所有这 50 种产品调用另一个 api。我已经给出了下面的代码。
唯一的限制是在第一页响应上,应该调用响应 50 的 api.. 就像 product?product=1 。下一个 50 只应在前 50 个 api 调用后调用
for (let index = 0; index < response.length; index++) {
const element = response[index];
//Here call api for one item
axios(config)
.then(function (elemen t) {
// Here i have got 50 products
})
.catch(function (error) {
console.log('err',err);
})
}
【问题讨论】:
标签: javascript node.js promise axios es6-promise