从Array.map()循环退出

时间:2020-10-22 11:05:54

标签: node.js express promise async-await cheerio

我有以下代码

const getCompanies = async (searchURL) => {
    const html = await rp(baseURL + searchURL);
    const businessMap = cheerio('a.business-name', html).map(async (i, e) => {
        const phone = cheerio('p.phone', innerHtml).text();
        if (phone == 123) {
            exit;
        }
        return {
            phone,
        }
    }).get();
    return Promise.all(businessMap);
};

如果我的条件匹配,我想退出循环。有什么办法,如果条件匹配,则立即返回数据。并停止执行循环

2 个答案:

答案 0 :(得分:2)

您的用例将更适合Array.some,而不是Array.map

some()方法测试数组中的至少一个元素是否通过了由提供的函数实现的测试。它返回一个布尔值。

因此,只要数组中的任何项目符合条件,它就会立即停止执行。 您可以在旁边使用外部变量来捕获匹配的值,例如:

const getCompanies = async (searchURL) => {
    const html = await rp(baseURL + searchURL);
    let businessMap;
    cheerio('a.business-name', html).some(async (i, e) => {
            const phone = cheerio('p.phone', innerHtml).text();

            if(phone == 123) {
               // condition matched so assign data to businessMap here
               // and return true so that execution stops
              return true;
            }       
       });
    return Promise.all(businessMap);
    };

答案 1 :(得分:0)

businessMap是一个数组,没有什么可等待的。 一种更简单的方法是:

const getCompanies = async (searchURL) => {
  const html = await rp(baseURL + searchURL)
  let $ = cheerio.load(html) 
  const ps = $('a.business-name p.phone').get()
  return ps.map(p => $(p).text()).filter(phone => phone !== '123')
};
相关问题