Javascript 同步函数在异步函数中的影响
让我们设想一个异步函数,它首先加载一个文件,然后异步处理它。如果没有该文件,该函数将无法继续,因此我的假设是加载此文件可以同步完成(*): 对于不同的文件,可以多次调用Javascript 同步函数在异步函数中的影响,javascript,node.js,asynchronous,callback,Javascript,Node.js,Asynchronous,Callback,让我们设想一个异步函数,它首先加载一个文件,然后异步处理它。如果没有该文件,该函数将无法继续,因此我的假设是加载此文件可以同步完成(*): 对于不同的文件,可以多次调用asyncFnWithSyncCode: async.parallel([ (done) => { asyncFnWithSyncCode('a.json', done) }, (done) => { asyncFnWithSyncCode('b.json', done) }, (done) =>
asyncFnWithSyncCode
:
async.parallel([
(done) => { asyncFnWithSyncCode('a.json', done) },
(done) => { asyncFnWithSyncCode('b.json', done) },
(done) => { asyncFnWithSyncCode('c.json', done) }
], next)
我的问题是:这对性能有何影响?同步功能是否会导致其他readFileSync
s延迟?它会有影响吗
欢迎提供最佳实践、资源和意见。谢谢
(*)我知道我可以简单地使用asyncreadFile
-版本,但我真的很想知道它在这种特殊结构中是如何工作的
同步功能是否会导致其他readFileSyncs
延迟
对。NodeJS使用事件循环(作业队列)在单个线程上运行所有JavaScript代码,这是强烈鼓励使用异步系统调用而不是同步系统调用的原因之一
readFile
调度读取操作,然后在I/O层等待数据进入时让JavaScript线程上发生其他事情;当数据可用时,节点的I/O层为JavaScript线程排队一个任务,这就是最终调用readFile
回调的原因
相比之下,readFileSync
只保留一个JavaScript线程,等待文件数据可用。因为只有一个线程,所以它会保留代码可能执行的所有其他操作,包括其他readFileSync
调用
您的代码不需要使用readFileSync
(您几乎从不这样做);只需使用readFile
的回调:
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);
}
});
}
解释得很好。谢谢!
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);
}
});
}