当 catch 函数返回错误时,我想重新启动我的代码。
let ig = require('instagram-scraping')
module.exports.instagram = async (req, res) => {
ig.scrapeTag('postthisonmypersonalblogtoo').then(async result => {
let myPostCodes = [];
result.medias.forEach(content => {
if(content.owner_id == '10601516006'){
myPostCodes.push(content.shortcode);
}
})
await res.render('instagram', {
myPosts : myPostCodes
});
}).catch((err) => {
console.error(err);
// if(err){
//ig.scrapeTag('postthisonmypersonalblogtoo').then(async result => { ... } //do same things as above
}
})
}
我想这样做的原因是:有时ig.scrapeTag方法能找到我的帖子,但有时却找不到任何东西,并返回给我,所以当我遇到这个错误时,我想重新设置ig.scrapeTag来研究我在instagram上的帖子。
Error: Error scraping tag page "postthisonmypersonalblogtoo"
at Request._callback (C:\Users\Byte\Desktop\BLOG\node_modules\instagram-scraping\index.js:114:24)
at Request.self.callback (C:\Users\Byte\Desktop\BLOG\node_modules\request\request.js:185:22)
所以当我遇到这个错误时,我想重新设置ig.scrapeTag来重新研究我在instagram上的帖子。
(顺便说一句,对不起,我的英语不好,如果你们有其他instagram api的建议,请告诉我(api可以是官方的,也可以是非官方的,无所谓)
我会把scrape功能移到单独的函数中,并引入重试计数器来跟踪重试的次数。也不知道为什么你要混合和匹配 then/catch
与 async/await
. 我认为使用以下方法更易读,也更一致。async/await
到处都是。类似这样的。
let ig = require('instagram-scraping')
const MAX_RETRY_COUNT = 2;
async function scrapeInstagram() {
let retryCount = 0;
const scrapeTag = async () => {
try {
const result = await ig.scrapeTag('postthisonmypersonalblogtoo');
return result;
}
catch(e) {
if (retryCount < MAX_RETRY_COUNT) {
retryCount++;
scrapeTag();
} else {
throw e;
}
}
}
const result = await scrapeTag();
let myPostCodes = [];
result.medias.forEach(content => {
if(content.owner_id == '10601516006'){
myPostCodes.push(content.shortcode);
}
});
return myPostCodes;
}
module.exports.instagram = async (req, res) => {
try {
const myPostCodes = await scrapeInstagram();
await res.render('instagram', {
myPosts : myPostCodes
});
}
catch(e) {
console.log(e);
res.status(500).send("Could not load from Instagram")
}
}