search

Home  >  Q&A  >  body text

node.js - koa 获取eventproxy中异步的值,返回给前端?

  var _ = require('lodash');
  
  var redis = require("redis");
  
  var cheerio = require('cheerio');
  
  var router = require('koa-router')();
  
  var superagent = require('superagent');
  
  let eventproxy = require('eventproxy');
  
  
  var ep = new eventproxy();
  
  let rets = []
  var client = redis.createClient();
  
  client.on("error", function (err) {
      console.log("Error " + err);
  });
      
  
  router.get('/', async function (ctx, next) {
      let keys = JSON.parse(ctx.query.key).split(',').reverse()
      
      let kVals = [];
      
      keys.forEach(key=>{
          let url = encodeURI(`http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=${key}`)
          superagent.get(url)
                  .end((err,res)=>{
                      console.log(`fetch------${key}------successful-----`)
                      let $  = cheerio.load(res.text)
                      let datas = Array.from($(".result")).splice(0,5)
                      for (var i = datas.length - 1; i >= 0; i--) {
                          let data = {
                              title:$(datas[i]).find('.c-title').text(),    
                              author:$(datas[i]).find('.c-author').text(),
                              summary:$(datas[i]).find('.c-summary').text()
                          }
                          kVals.unshift(data)
                      }
                      ep.emit('news',kVals)
                  })
      })
  
      ep.after('news',keys.length,rets=>{
          rets = rets.map(ret=>{
              return(ret)
          })    
      })
  
  
      ctx.state = {
          title: '数据搜索结果页',
          ret:ret//如何获取异步的信息?
      };
      await ctx.render('results');
  })
  module.exports = router;
PHP中文网PHP中文网2786 days ago409

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-17 15:31:54

    This can be done using the asynchronous process control library async

    async.map(['file1','file2','file3'], fs.stat, function(err, results) {
        // results is now an array of stats for each file
    });

    reply
    0
  • Cancelreply