2015-12-22 3 views
2

Мне нужно разобрать 10 веб-страниц и поймать их основное содержимое. Поэтому я использую удобочитаемость узлов и не хочу переписывать одни и те же функции (только изменения URL) 10 раз. Наконец, я должен подсчитать длину контента. Как я могу это сделать, используя цикл или любые другие идеи? Теперь он выглядит:NodeJS. Асинхронный. Параллельная. Те же функции

for(var i=0; i<catchedUrl.length; i++){ 
    var data = {length: 0, count: 0}; 
    (function(i) { 
     read(catchedUrl[i], function(err, article, meta){ 
      if(err) throw err; 

      var content = article.content; 
      content = content.split(' '); 
      article.close(); 
      data.count += 1; 
      data.length += length; 
      // Send data to callback when functions done 
     }); 
    })(i); 
} 

ответ

2

Егора работает.

Вы также можете использовать co, чтобы избавиться от асинхронности:

$ npm i --save co thunkify

var co = require('co'); 
var read = require('node-readability'); 
var thunkify = require('thunkify'); 

var cachedUrls = [ 
    'http://stackoverflow.com/questions/34414539/elasticsearch-filtering-mulitple-documents-with-same-term', 
    'http://stackoverflow.com/questions/34414537/selecting-multiple-values-with-multiple-where-clauses', 
    'http://stackoverflow.com/questions/34414536/how-to-create-functional-test-directory-in-grails', 
    'http://stackoverflow.com/questions/34414534/azure-active-directory-application-key-renewal', 
    'http://stackoverflow.com/questions/34414532/store-facebook-credential-in-android-for-google-smart-lock-password', 
    'http://stackoverflow.com/questions/34414531/ssis-read-flat-file-skip-first-row', 
    'http://stackoverflow.com/questions/34414529/set-non-database-attribute-for-rails-model-without-attr-accessor', 
    'http://stackoverflow.com/questions/34414525/excel-code-blocking-other-excel-sheets-to-open', 
    'http://stackoverflow.com/questions/34414522/app-crash-when-network-connection-gone', 
    'http://stackoverflow.com/questions/34414520/nest-input-inside-label-with-simple-form-and-rails-4' 
]; 

co(function *() { 

    var data = { 
     length: 0, 
     count: 0 
    }; 

    for (var i = 0, n = cachedUrls.length; i < n; i++) { 

     let response = yield thunkify(read)(cachedUrls[i]); 

     data.length += response['0'].content.split(' ').length; 
     data.count++;  
    } 

    return data; 

}).then(function(value) { 
    console.log('final value:', value); 
}); 
+0

Вы делаете использование 'co' здесь. Функция генератора сама по себе ничего не помогает. – Bergi

+1

@ Берги, я сформулировал это по-другому. –

3

Вы можете использовать async модуль для упрощения цикла. Кроме того, пожалуйста, посмотрите на .bind() функции bind documentation

Так пример кода в таком случае может выглядеть примерно так

var async = require('async'); 

function step(number, callback) { 
    [enter code here] 
    callback(); 
} 

module.exports = (job, done) => { 
    var _pages = [URLS]; 
     async.eachSeries(_pages, (link, callback)=> { 
      step(link, callback); 
     },()=> done()); 
    }); 

}; 

С наилучшими пожеланиями, ответ Егор