天青node.js请求,响应 – 寻求一些澄清

我正在使用Azure移动服务 – NodeJS后端,编程时,我总是面对这个疑问 – 让我解释一下使用下面的代码片段

//-------------------------------------------------------------------------- function addUserToDB(request, response){ ///some code here var theUser = request.user; ///get the user's entity object try { objAppUser = buildAppUserEntityObj(theUser, request); //for simplicity sake, lets say this is not asynchronous function } catch (err) { console.log ('error in addUserToDB when calling buildAppUserEntityObj'); //****????**** request.respond(statusCodes.BAD_REQUEST, err); return; // ##????## is a 'return' needed here to avoid the execution of the code below, or should I assume that the function will return once request is responded (request.respond) in above line. } ....code to add userEntity to DB //some more code in case of successful try above, can I assume there is no way this code will be reached in case of error in the above try-catch // ofcourse I can move this code in the 'try' block above, but I am just trying to understand what happens if above try ends in catch block for some reason and there is no 'return' at the end that catch block. } //-------------------------------------------------------------------------- function buildAppUserEntityObj(user, request) { if ( user.level === 'anonymous' ) { //ideally this would be called in above function, but I am putting this here just to throw an example. console.error('Anonymous User' ); request.respond(statusCodes.BAD_REQUEST, message); //will this request.respond will send the response to client immediately, or will it be passed on as error the try-catch of above 'addUserToDB' function return; // ##????## also, is 'return' needed here to avoid the execution of the code below, } ....code to build a User entity object based on some business logic } //-------------------------------------------------------------------------- 

我想,这一切都归结为三个问题:
1.两个地方是否需要“返回”(在上述两个函数中用##?##标记)?
2.如果user.level ==='匿名',将会logging该消息(由// **** ???? ****标记)
3. request.respond vs response.send,有什么区别?

我相信这些疑惑是因为我缺乏透彻的expression知识,所以当我再次通过azure / express.js文档的时候,我想我会把这个问题抛给专家群体来得到更清晰的解释。

非常感谢。

第一

在第二个return (buildAppUserEntityObj函数的buildAppUserEntityObj ,我相信你希望它是:

 throw new Error("Anonymous user is not allowed") 

否则,即使用户是匿名的,你的catch代码永远也不会执行。


你需要第一个return; ,否则会继续执行下面的代码。

第二

如果您修复第一段中描述的代码,将会logging消息。

第三

在标准的Node.js http模块中没有request.respond 。 你能澄清一下,你在用什么模块? 无论如何,该模块的API将回答你的问题。