Exit from Array.map() loop

Viewed 222

I have following code

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

I want to exit in loop if my condition match. is there any way so if condition match then return the data right away. and stop execution of the loop

2 Answers

Your use case will be more suited to Array.some instead of Array.map

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

So it stops execution as soon as any of the item in the array matches the condition. You can use an external variable alongside to catch the matched value, e.g:

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

businessMap is an array and there's nothing to await. A simpler way to do this is:

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