映射一个数组并在里面调用async函数



映射数组并调用具有所有项的异步函数的方法是什么?

const scrape = async (url) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const [el] = await page.$x('//*[@id="page-body"]/h2/a');
const txt = await el.getProperty('textContent');
const rawTxt = await txt.jsonValue();
//here do an another thing with an other function
const obj = formatRes(rawTxt);

browser.close();

return obj; 
};

第二个功能:

const formatRes = (res) => {
[...]
return obj;
}

调用第一个函数:

linksB.map(item => scrape(item));

linksB是一个URL数组。

我想把所有从scrape返回的对象放在一个新的数组中。

假设我们有一个链接数组,您想在其中向每个链接发出请求,那么我们可以在Promise.all中执行数组map

const urls = [ 'url1...', 'url2...', 'url3...' ];
const responses = await Promise.all(urls.map(url => makeRequest(url)))
// use responses array where each response map exactly to each url's response

最新更新