[英]Is it possible to handle both async and sync function results inside a sync function in node.js?
我正在处理一个较少预处理,手写笔等的库。预处理器本质上既可以是异步的,也可以是同步的。 由于结果将仅在构建阶段使用,因此在此处编写阻塞代码不是问题。
因为大多数预处理器都是同步的,并且库期望同步函数沿链运行,所以我想知道是否有可能将预处理器函数包装在可以处理预处理函数的同步和异步结果的同步函数中?
基本上可以以某种方式做这样的事情吗?
syncFn = function(contents) {
var res = syncOrAsyncFn(contents, function(err, contents) {
res = contents
})
// .. do some magic here that waits for the results of syncOrAsyncFn
return res; // Return the result from a function that could be async or sync
}
对不起,那是不可能的。 每当代码块运行时,它们之间就什么也不能运行,即NodeJS中没有真正的并行性。 因此,无论您执行什么操作: res = contents
syncFn
line只能在syncFn
完成任何操作后(即在所有同步操作完成代码块中的工作之后) syncFn
。
这迫使NodeJS程序员使用回调模式,例如:
syncFn = function(contents, callback) {
syncOrAsyncFn(contents, function(err, contents) {
callback(contents);
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.