我有一种情况,我在调用具有分页的API.
我想做的是下面的内容,一次一页.
>调用API页面1
>对于响应中的每个项目,调用Promise以获取更多数据并存储在数组中
>将数组发送到API
>重复直到所有页面都完成
我目前拥有的是以下内容,但是我不确定使如何进行处理,这可能会使此操作过于复杂.
export const importData = async() {
const pSize = 15;
const response = await getItems(pSize,1);
const noPage = Math.ceil(response.totalMerchandiseCount/pSize);
for (let i = 1; i < noPage; i++) {
const items = [];
const data = await getItems(pSize,i);
await async.each(data.merchandiseList,async(i,cb) => {
const imageURL = await getImageURL(i.id,i.type);
items.push({
id: i.id,imageURL: imageURL,});
cb();
},async() => {
return await api.mockable('sync',items);
});
}
}
export const getImageURL = async(id,type) => {
let url = `https://example.com/${id}`;
return axios.get(url)
.then((response) => {
const $= cheerio.load(response.data);
// do stuff to get imageUrl
return image;
})
.catch((e) => {
console.log(e);
return null;
})
};
最佳答案
如果这些都是串行的,那么您可以使用for-of循环:
export const importData = async() {
const pSize = 15;
const response = await getItems(pSize,1);
const noPage = Math.ceil(response.totalMerchandiseCount/pSize);
for (let i = 1; i < noPage; i++) { // Are you sure this shouldn't be <=?
const items = [];
const data = await getItems(pSize,i);
for (const {id,type} of data.merchandiseList) {
const imageURL = await getImageURL(id,type);
items.push({id,imageURL});
}
await api.mockable('sync',items);
}
}