cari

Rumah  >  Soal Jawab  >  teks badan

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 hari yang lalu407

membalas semua(1)saya akan balas

  • PHPz

    PHPz2017-04-17 15:31:54

    这个使用异步流程控制库 async 就可以了

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

    balas
    0
  • Batalbalas