我正在尝试使用一组 URL 串行运行 Node js Lighthouse 函数(一次一个)。我的问题是,每当我循环遍历数组时,Lighthouse 都会立即运行所有 URL,如果您有一个非常大的 URL 数组,我认为这是有问题的。
代码:
for(let url of urls) {
function launchChromeAndRunLighthouse(url, opts, config = null) {
return chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(chrome => {
opts.port = chrome.port;
return lighthouse(url, opts, config).then(results => {
return chrome.kill().then(() => results.lhr)
});
});
}
}
launchChromeAndRunLighthouse('https://example.com', opts).then(results => {
// Use results!
});
请帮忙!感谢您抽出时间!
最佳答案
您的答案是正确的,但可以改进。由于您可以访问 async
和 await
,因此您应该充分利用它来使代码更简洁:
async function launchChromeAndRunLighthouse (url, opts, config = null) {
const chrome = await chromeLauncher.launch({chromeFlags: opts.chromeFlags});
opts.port = chrome.port;
const { lhr } = await lighthouse(url, opts, config);
await chrome.kill();
return lhr;
}
async function launchAudit (urls) {
for (const url of urls) {
const results = await launchChromeAndRunLighthouse(url, opts);
// Use results!
};
}
launchAudit(urls);
关于javascript - 如何串行运行基于 Promise 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54132106/