与Cheerio的异步地图

时间:2017-05-23 14:10:42

标签: node.js async.js

我使用Async和Cheerio时遇到了问题。

我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    [...]
    this.mBackground = (DrawLayout) findViewById(R.id.fl);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int action = event.getActionMasked();
    final float eventX = event.getRawX();
    final float eventY = event.getRawY();
    if(dotEnabled){
        dot.setX(eventX);
        dot.setY(eventY);
    }
    if(directionSet){
        direction.setX(eventX);
        direction.setY(eventY);
    }
    this.mBackground.declarePath(**Here you have to pass the coordinates of your points**);
return false;

问题:我无法获取事件......在var request = require('request'), cheerio = require('cheerio'), _ = require('lodash'), sitesJson = require('./websites.json'), Sequelize = require('sequelize'), asyncFn = require('async'); asyncFn.map(sitesJson.sites, function(site) { request(site.url, function (error, response, body) { $ = cheerio.load(body); $(site.eventsQuery).each( function() { var event = { title : eval(site.titleQuery), description : eval(site.descriptionQuery), thumbnail : eval(site.thumbnailQuery), lat : eval(site.latQuery), lng : eval(site.lngQuery) }; console.log(event); // not null return event; }); }); }, function(err, results) { console.log(results); // null }); 函数中,事件对象不为空。

1 个答案:

答案 0 :(得分:1)

问题是你在forEach函数中返回事件,所以它没用。你也错过了map的iteratee函数内的回调。

这应该有效:

var request    = require('request'),
    cheerio    = require('cheerio'),
    sitesJson  = require('./websites.json'),
    asyncFn    = require('async');

asyncFn.map(sitesJson.sites, function(site, cb) {

  request(site.url, function (error, response, body) {

    $ = cheerio.load(body);

    var events = $(site.eventsQuery).map(function(event) {
      return {
        title : eval(site.titleQuery),
        description : eval(site.descriptionQuery),
        thumbnail : eval(site.thumbnailQuery),
        lat : eval(site.latQuery),
        lng : eval(site.lngQuery)
      }
    });

    cb(null, events);

  });

}, function(err, results) {

  console.log(results); // null

});

此外,eval不是必需的,应该有另一种方式......

最重要的是,如果您需要处理多个网址,可能需要考虑使用mapLimit