gpt4 book ai didi

javascript - 如何串行运行基于 Promise 的函数

转载 作者:行者123 更新时间:2023-12-03 00:25:00 25 4
gpt4 key购买 nike

我正在尝试使用一组 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!
});

请帮忙!感谢您抽出时间!

最佳答案

您的答案是正确的,但可以改进。由于您可以访问 asyncawait,因此您应该充分利用它来使代码更简洁:

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/

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