遍历异步功能 [英] Iterate over async function

查看:219
本文介绍了遍历异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用该模块cherio从网站获取数据的功能。

现在,我想在关键字的数组遍历这个功能,收集中间结果在一个数组命名的统计中,最后通过的console.log打印统计数据阵列的结果到控制台()

每当我运行此脚本,它迅速触发异步功能,并打印一个空数组统计。

现在我的问题:我怎么能等待异步函数来完成,这样我可以打印数组来安慰它填充的时候/成品

我用Google搜索了很多,搜索堆栈溢出。似乎有很多方法来实现我的目标,但什么是节点的最地道的方式做到这一点?

下面是我解决它的方式:

  VAR请求=要求(请求),
    cheerio =要求(cheerio),
    BASE_URL =htt​​p://de.indeed.com/Jobs?q=; //后等号,例如:西纳特拉和放大器; L =/ *搜索语法:
    - http://de.indeed.com/Jobs?q=node&l=berlin&radius=100
    -
    -
* /// //
VAR search_words = [的Django,巨蟒,瓶,
                    铁轨,​​红宝石,
            节点,JavaScript的,angularjs,反应,
            的java,Grails的,常规,
            PHP,symfony中,laravel
            ];变种计数器= 0;
VAR统计= [];
功能getStats(关键字){
    URL = BASE_URL +关键字+&放大器; L =;
    请求(URL,功能(呃,防尘面具,身){
    如果(!ERR){
        $ = cheerio.load(体);
        数据= $(#SEARCHCOUNT)[0]。儿童[0] .data.split().reverse()[0];        stats.push([关键字,资料]);
        反++;
    }
    //列表完成?
    如果(计数器=== search_words.length){
        的console.log(统计);
    }
    });
}对于(VAR J = 0; J< = search_words.length; J ++){
    getStats(search_words [J]);
}


解决方案

无极是用于处理异步操作的最佳解决方案。

\r
\r

Promise.all(search_words.map(功能(关键字){\r
  返回新希望(函数(解析,拒绝){\r
    请求(BASE_URL +关键字+&放大器; L =功能(呃,防尘面具,身){\r
      如果(ERR){\r
        回拒绝(ERR);\r
      }\r
      $ = cheerio.load(体);\r
      解析([关键字,$(#SEARCHCOUNT)[0]。儿童[0] .data.split().reverse()[0]);\r
    });\r
  });\r
}))。然后(功能(统计){\r
  的console.log(统计);\r
});

\r

\r
\r

I have a function that uses the module cherio to get data from a website.

Now I'd like to iterate this function over an array of keywords, collect the intermediate results in an array named stats and finally print the results of the stats array to the console via console.log()

Whenever I run this script it triggers the async function quickly and prints an empty stats array.

Now my question: How can I wait for the async functions to complete so that I can print the array to console when it's populated / finished.

I have googled a lot and searched stack overflow. There seem to be many ways to accomplish my goal, but what is the most idiomatic way in node to do this?

Here is the way I solved it:

var request = require("request"),
    cheerio = require("cheerio"),
    base_url = "http://de.indeed.com/Jobs?q=";  // after equal sign for instance:   sinatra&l=

/* search syntax:
   - http://de.indeed.com/Jobs?q=node&l=berlin&radius=100
   - 
   - 
*/ 

// //
var search_words = ["django", "python", "flask", 
                    "rails", "ruby",
            "node", "javascript", "angularjs", "react",
            "java", "grails", "groovy",
            "php", "symfony", "laravel"
            ];

var counter = 0;
var stats = [];


function getStats(keyword) {
    url = base_url + keyword + "&l=";
    request(url, function(err, resp, body) {
    if(!err) {
        $ = cheerio.load(body);
        data = $("#searchCount")[0].children[0].data.split(" ").reverse()[0];

        stats.push([keyword, data]);
        counter++;
    }
    // list complete?
    if (counter === search_words.length) {
        console.log(stats);
    }
    });
}

for (var j=0; j<= search_words.length; j++) {
    getStats(search_words[j]);
}

解决方案

Promise is the best solution for handling asynchronous operations.

Promise.all(search_words.map(function(keyword) {
  return new Promise(function(resolve, reject) {
    request(base_url + keyword + "&l=", function(err, resp, body) {
      if (err) {
        return reject(err);
      }
      $ = cheerio.load(body);
      resolve([keyword, $("#searchCount")[0].children[0].data.split(" ").reverse()[0]]);
    });
  });
})).then(function(stats) {
  console.log(stats);
});

这篇关于遍历异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆