简体   繁体   English

Node.js回调以及何时退出

[英]Node.js callbacks and when to exit

I'm working my way through Smashing Node.js, which seems great so far, but there's something about writing async code and using callbacks that I don't understand. 我正在通过Smashing Node.js进行工作,到目前为止看起来还不错,但是关于编写异步代码和使用我不理解的回调有些事情。

If I have code like this: 如果我有这样的代码:

myObject.doSomethingAsync( errorCallback );
// all done, want to exit here, but errorCallback may be called
…

function errorCallback(args) {
    // do something that takes a few seconds
}

Keep in mind that I do mean exit; 请记住,我意思退出; this is a scheduled task not a server. 这是计划任务,而不是服务器。

How do I know when to exit? 我怎么知道什么时候退出? It'd be easier if errorCallback was always called, but in the case of one module I'm using, it's not. 如果始终调用errorCallback会更容易,但是在我使用的是一个模块的情况下,事实并非如此。 Is it odd to have this kind of conditional callback? 有这种条件回调很奇怪吗? How do I handle this cleanly? 我该如何清洁处理?

The convention in Node is for callbacks to accept an Error object as the first argument. Node中的约定是让回调函数接受Error对象作为第一个参数。

http://blog.gvm-it.eu/post/22040726249/callback-conventions-in-node-js-how-and-why http://blog.gvm-it.eu/post/22040726249/callback-conventions-in-node-js-how-and-why

Your callback should get called on both success and failure. 您的回调应同时调用成功和失败。 On success the err object will be null. 成功时,err对象将为null。

Of course this is the convention, but there are probably plenty of modules that disregard this convention. 当然这是约定,但是可能有很多模块不考虑该约定。 You should either attempt to fix the module you are using or use a different one. 您应该尝试修复正在使用的模块,或者使用其他模块。

Node will exit the process when nothing is left to do. 当什么都不做时,节点将退出进程。 If you need to do something before the exit occurs you can listen for process.exit. 如果您需要在退出之前做点事情,可以监听process.exit。

http://nodejs.org/api/process.html#process_event_exit http://nodejs.org/api/process.html#process_event_exit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM