Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将同步代码插入异步_Javascript_Node.js_Multithreading_Asynchronous_Lighthouse - Fatal编程技术网

Javascript 将同步代码插入异步

Javascript 将同步代码插入异步,javascript,node.js,multithreading,asynchronous,lighthouse,Javascript,Node.js,Multithreading,Asynchronous,Lighthouse,我正在对大约50个站点的列表进行测试。我只是在一个.forEach循环中运行它,如果我理解的话,它是阻塞的,也就是同步的。然而,我最终一次旋转了50个Chrome Canary实例。在我对这些事情的有限理解中,我认为线程是同步启动的,但是节点可以将线程传递给内核,并愉快地启动下一个线程。再说一次,这只是我对正在发生的事情的理解 我正在使用我从某处抄袭的函数: function launchChromeAndLighthouse(url, opts, config = null) { retu

我正在对大约50个站点的列表进行测试。我只是在一个.forEach循环中运行它,如果我理解的话,它是阻塞的,也就是同步的。然而,我最终一次旋转了50个Chrome Canary实例。在我对这些事情的有限理解中,我认为线程是同步启动的,但是节点可以将线程传递给内核,并愉快地启动下一个线程。再说一次,这只是我对正在发生的事情的理解

我正在使用我从某处抄袭的函数:

function launchChromeAndLighthouse(url, opts, config = null) {
  return chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(chrome => {
    opts.port = chrome.port;
    return lighthouse(url, opts, config).then(results =>
      chrome.kill().then(() => results));
  });
}
我在循环中尝试了nextTick:

asyncFuncs().then( async (sites) => {
  sites.forEach( (site) => {
    process.nextTick(launchChromeAndRunLighthouse(site.url, opts))
  })
})
但这仍然会产生大量的Chrome实例。如何在一个lighthouse完成时暂停执行?

由于launchChromeAndRunLighthouse在完成时返回标记承诺,如果您希望一次只连续运行一个,可以切换到for循环并使用wait:

如果您试图收集所有结果:

asyncFuncs().then( async (sites) => {
    let results = [];
    for (let site of sites) {
      let r = await launchChromeAndRunLighthouse(site.url, opts);
      results.push(r);
    }
    return results;
}).then(results => {
    // all results here
}).catch(err => {
    // process error here
});
如果您希望一次运行N个chrome实例,使其最初启动N个实例,然后每次一个实例完成时,您都会启动下一个正在等待的实例,这对于跟踪有多少实例正在运行更为复杂。有一个助手函数调用pMap或mapConcurrent,可以在以下答案中为您实现这一点:

在其中还具有并发控制

asyncFuncs().then( async (sites) => {
    let results = [];
    for (let site of sites) {
      let r = await launchChromeAndRunLighthouse(site.url, opts);
      results.push(r);
    }
    return results;
}).then(results => {
    // all results here
}).catch(err => {
    // process error here
});