azure node.js请求,响应 - 寻求一些澄清

时间:2014-12-02 15:32:19

标签: node.js azure express azure-mobile-services

我正在使用Azure Mobile服务-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 ==='匿名',则会记录消息(标记为// **** ???? ****) 3. request.respond vs response.send,这是什么区别?

我相信这些怀疑是因为我缺乏完整的expressJS知识,所以当我再次通过azure / express.js文档时,我想我会向专家社区提出疑问以获得更清楚的解释。

非常感谢。

1 个答案:

答案 0 :(得分:1)

第一

在第二个returnbuildAppUserEntityObj函数的insode中,我相信你希望它是:

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

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


您需要第一个return;,否则它将继续执行以下代码。

第二

如果您修复了 First 段落中描述的代码,则会记录消息。

第三

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