Functional programming 带ramda.js(函数式编程)的爬虫程序

Functional programming 带ramda.js(函数式编程)的爬虫程序,functional-programming,cheerio,ramda.js,Functional Programming,Cheerio,Ramda.js,我正在尝试从TMDB网站抓取电影数据。我用纯javascript完成了我的代码,但我想通过使用ramda.js将代码更改为函数式编程风格 我在下面附上了我的代码。我想去掉for循环(如果可能的话)并使用R.pipe函数 (async () => { for (let i = 0; i < 1000; i++) { (() => { setTimeout(async () => { let year = startYr + Math.

我正在尝试从TMDB网站抓取电影数据。我用纯javascript完成了我的代码,但我想通过使用ramda.js将代码更改为函数式编程风格

我在下面附上了我的代码。我想去掉for循环(如果可能的话)并使用R.pipe函数

(async () => {
  for (let i = 0; i < 1000; i++) {
    (() => {
      setTimeout(async () => {
        let year = startYr + Math.floor(i / 5);
        await request.get(path(year, i % 5 + 1), async (err, res, data) => {
          const $ = cheerio.load(data);
          let list = $('.results_poster_card .poster.card .info .flex a');
          _.forEach(list, (element, index) => {
            listJSON.push({
              MovieID: $(element).attr('id').replace('movie_', ''),
              Rank: (i % 5) * 20 + index + 1,
              Year: year
            });
          });
          if(i === 1000 - 1) {
            await pWriteFile(`${outputPath}/movieList.json`, JSON.stringify(listJSON, null, 2));
          }
        });
      }, 1000 * i);
    })(i);
  }
})().catch(error => console.log(error));
(异步()=>{
for(设i=0;i<1000;i++){
(() => {
setTimeout(异步()=>{
年份=起始日期+数学楼层(i/5);
等待请求。获取(路径(年份,i%5+1),异步(错误,恢复,数据)=>{
const$=cheerio.load(数据);
let list=$('.results_poster_card.poster.card.info.flex a');
_.forEach(列表,(元素,索引)=>{
listJSON.push({
MovieID:$(element.attr('id').replace('movie_u',''),
排名:(i%5)*20+指数+1,
年份:年份
});
});
如果(i==1000-1){
等待pWriteFile(`${outputPath}/movieList.json`,json.stringify(listJSON,null,2));
}
});
},1000*i);
})(i) );
}
})().catch(error=>console.log(error));

您可以使用Ramda
range()
函数替换循环

R.range(0,1000);

这将为您提供一组整数(您的
i
),您可以使用这些整数(
map()
或任何您需要的整数)。

步骤:

const process = index => sleep(1000)
   .then(() => makeRequest(index))
   .then(processData);

R.range(0, 1000)
   .reduce(
       (prev, actual) => prev.then(() => process(actual),
       Promise.resolve()
   ) // Sequential
   .then(printResult);

R.range(0, 1000)
   .map(process) // Parallel
   .then(printResult);
1-在小函数中分解代码
2-停止使用
async
等待
并使用
承诺。然后(其他功能)

3-使用promise时,您可以创建如下函数:
const sleep=(time)=>newpromise(resolve=>setTimeout(resolve,time))

示例:

const process = index => sleep(1000)
   .then(() => makeRequest(index))
   .then(processData);

R.range(0, 1000)
   .reduce(
       (prev, actual) => prev.then(() => process(actual),
       Promise.resolve()
   ) // Sequential
   .then(printResult);

R.range(0, 1000)
   .map(process) // Parallel
   .then(printResult);

TMDB有api,不需要对它进行爬网:感谢您的评论,我只是为了学习而尝试这么做。