Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lesson5 并发控制, 我写了一个简单的实现并发 5 条的控制函数 #157

Open
ocian opened this issue Apr 2, 2018 · 0 comments

Comments

@ocian
Copy link

ocian commented Apr 2, 2018

const superagent = require('superagent');
const cheerio = require('cheerio');
const url = require('url');
const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
  const sourceUrl = 'https://cnodejs.org';
  const hrefArray = [];
  const resultArray = [];
  
  superagent.get(sourceUrl).then(received => {
    const $ = cheerio.load(received.text);
    $('#topic_list .user_avatar').each((index, current) => {
      hrefArray.push(url.resolve(sourceUrl, $(current).attr('href')));
    });
    
    let stat = 0;
    
    function promiseExecute(url) {
      stat += 1;
      console.log(`当前正在执行的任务数量:  ${stat}`);
      return superagent.get(url)
        .then(current => {
          let _$ = cheerio.load(current.text);
          let userMsg = { user: $(_$('#content .dark')[0]).text(), score: _$('#content .big').text().trim() };
          resultArray.push(userMsg);
          stat -= 1;
        })
    }
    
    function parallelExecute(cb, paramArray, num, handle) {
      let tempArray = paramArray.concat();
      let endFlag = 1;
      function recursionHandle() {
        let paramItem = tempArray.pop();
        if(!paramItem) {
          endFlag += 1;
          if(endFlag === num) { cb(); }
          return;
        }
        return new Promise(() => {
          handle(paramItem)
            .then(() => { recursionHandle(); })
            .catch(err => { throw err; });
        })
      }
      for(let i = num - 1; i >= 0; i -= 1) { recursionHandle(); }
    }
    
    function resSend() {
      res.send(JSON.stringify(resultArray));
      console.log(resultArray);
    }
    
    parallelExecute(resSend, hrefArray, 5, promiseExecute);
  })
  .catch(err => {
    console.log(err)
  });
});

app.listen(3000, () => {
  console.log('3000 port listening...')
});

依赖安装

yarn add cheerio express superagent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant