【问题标题】:Exit from Array.map() loop退出 Array.map() 循环
【发布时间】:2021-02-05 09:26:06
【问题描述】:

我有以下代码

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

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

【问题讨论】:

  • .map 中使用async 是否有原因
  • 因为我在使用await,所以会有结果
  • 我没有看到你在使用 await
  • 见第二行 const html = await rp(baseURL + searchURL);
  • 我的问题是你为什么在.map() 中使用async 而不是rp

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


【解决方案1】:

您的用例将更适合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);
    };

【讨论】:

  • 我也必须返回值
  • 我也在获取更多数据。一旦条件匹配,我也需要返回这些数据。但上面的代码对我不起作用:(
  • @sunnyjindal 如果您需要返回所有匹配的值,那么您需要使用 map 但如果您只需要第一个匹配的值,那么上面的代码将 bussinessMap 分配给第一个匹配并终止循环
  • 注意async函数总是返回一个Promise,它会被认为是true(即元素通过了测试),并让.some(async ...)在测试第一个元素后停止执行。例如,[1, 2, 3].some(x => console.log(x)) 打印 1、2、3 并返回 false,但 [1, 2, 3].some(async x => console.log(x)) 仅打印 1 并返回 true
  • @MetaPakistani 。如果匹配,我只需要返回一个结果。但我必须返回一些价值。我使用了你的代码,但它不起作用
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多