同步function在asynchronousfunction中的影响
让我们想象一个asynchronous函数,它首先加载一个文件,然后用它asynchronous执行。 该函数不能继续没有文件,所以我的假设是,加载此文件可以完成同步(*):
const asyncFnWithSyncCode(filePath, next) { // Load file const file = fs.readFileSync(filePath) // Continue to process file with async functions // ... next(null, processedFile) }
asyncFnWithSyncCode
可以针对不同的文件多次调用:
async.parallel([ (done) => { asyncFnWithSyncCode('a.json', done) }, (done) => { asyncFnWithSyncCode('b.json', done) }, (done) => { asyncFnWithSyncCode('c.json', done) } ], next)
我的问题是:这如何影响性能? sync函数是否会导致其他readFileSync
被延迟? 它会有影响吗?
最好的做法,资源和意见是受欢迎的。 谢谢!
(*)我知道我可以简单地使用async readFile
-version,但我真的很想知道它是如何在这个特殊的结构中工作的。
同步function是否会导致其他
readFileSyncs
被延迟?
是。 NodeJS使用事件循环(作业队列)在单个线程上运行所有JavaScript代码,这是强烈build议使用asynchronous系统调用的原因之一。
readFile
调度读取操作,然后在I / O层等待数据进入的同时让JavaScript线程上发生其他事情; 当数据可用时,节点的I / O层会为JavaScript线程排队,这就是最终使您的readFile
callback被调用的原因。
相比之下, readFileSync
支持一个单独的JavaScript线程,等待文件数据可用。 由于只有一个线程,所以你的代码可能会做其他事情,包括其他的readFileSync
调用。
你的代码不需要使用readFileSync
(你几乎从不这样做); 只要使用readFile
的callback:
const asyncFnWithSyncCode(filePath, next) { // Load file fs.readFile(filePath, function(err, file) { if (err) { // ...handle error... // ...continue if appropriate: next(err, null); } else { // ...use `file`... // Continue to process file with async functions // ... next(null, processedFile); } }); }