gpt4 book ai didi

node.js - 退出 Array.map() 循环

转载 作者:行者123 更新时间:2023-12-04 08:42:45 24 4
gpt4 key购买 nike

我有以下代码

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);
};
如果我的条件匹配,我想退出循环。有什么办法,如果条件匹配,则立即返回数据。并停止执行循环

最佳答案

您的用例将更适合 Array.some而不是 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.


因此,只要数组中的任何项目与条件匹配,它就会停止执行。
您可以在旁边使用外部变量来捕获匹配的值,例如:
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);
};

关于node.js - 退出 Array.map() 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64480933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com