Iterate over async function

前端 未结 3 727
闹比i
闹比i 2021-01-07 00:17

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

3条回答
  •  一生所求
    2021-01-07 01:04

    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);
    });

提交回复
热议问题