像这样的东西在异步代码中工作吗?
regular = 'a string';
enriched = enrichString(regular);
sys.puts(enriched);
function enrichString(str){
//run str through some regex stuff or other string manipulations
return str;
}
现在它似乎正在做我希望它做的事情,但我不知道它是否安全。有时这会导致未定义吗?我需要做这样的事情吗:
regular = 'a string';
enriched = enrichString(regular, function(data){sys.puts(data);});
function enrichString(str, cb){
//run str through some regex stuff or other string manipulations
cb(str);
}
谢谢您的帮助!
regular = 'a string';
enriched = enrichString(regular);
sys.puts(enriched);
function enrichString(str){
//run str through some regex stuff or other string manipulations
return str;
}
Right now it seems to be doing what I hoped it would do but I don't know if its safe. Could this result in undefined sometimes? Do I need to do something like:
regular = 'a string';
enriched = enrichString(regular, function(data){sys.puts(data);});
function enrichString(str, cb){
//run str through some regex stuff or other string manipulations
cb(str);
}
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你应该没问题。计算代码的直接运行本质上不是异步的。当某些操作涉及外部资源(文件 I/O、网络操作、某些操作系统交互等)时,需要回调。
No, you should be fine. Straight runs of computational code are inherently not asynchronous. Callbacks are needed when there's some action involving external resources — file I/O, network operations, some operating system interactions, etc.
如果您进行异步非阻塞调用,则仅需要回调。
如果
enrich
被阻塞,则安全。例如阻塞,所以这样做是安全的。其中 as
使用非阻塞 IO 并且不安全。您想要做的是这样的:
请注意
enriched = richString(regular, sys.puts(data));
不起作用,因为您传入了
sys.puts(data )
作为函数参数(数据也未定义!)您需要传入一个函数。
You only need callbacks if your making asychronous non-blocking calls.
Is safe if
enrich
is blocking. For exampleis blocking so it's safe to do this. Where as
Uses non blocking IO and is not safe. What you want to do is this :
Notice that
enriched = enrichString(regular, sys.puts(data));
Does not work because your passing in the return value of
sys.puts(data)
as your function parameter (data is undefined aswell!)You need to pass in a function.
只是为了添加 Pointy 的响应,人们有时会使用 process.nextTick (或在浏览器中 setTimeout(fn,0))强制异步行为 - 这会强制当前执行上下文屈服。例如: https://github.com/caolan/async /blob/master/lib/async.js#L408-410
Just to add on Pointy's response, people sometimes force asynchronous behavior with process.nextTick (or in the browser setTimeout(fn,0)) - this forces the current execution context to yield. Ex: https://github.com/caolan/async/blob/master/lib/async.js#L408-410