【问题标题】:Async Processing for Node.js POST Request ResponseNode.js POST 请求响应的异步处理
【发布时间】:2019-01-26 18:31:49
【问题描述】:

我对@9​​87654322@ 比较陌生,我正在创建一个服务器,该服务器将接受来自移动应用程序的POST 请求,该移动应用程序的主体包含一个凭据,然后将通过GET 验证另一个服务器。如果GET 响应验证凭据,则提取UID 并调用firebase admin SDK 以创建自定义令牌。这是代码的 sn-p 和两个调用的函数,(a) 验证凭据,(b) 生成自定义令牌。

//Listen for app to POST Credential
  app.post('/', function(request, response) {
    console.log('Request Body: ',request.body);
    var Credential = request.body;

    //Validate Credential
    validateCredential(Credential)

    //Get Authorization Token
    getToken(userID)

    //Return Token for POST Response
    response.set('Content-Type','Text');
    response.end(firebaseAuthToken);

  });
  //Create listener for POST function
  app.listen(port, function() {
    console.log('AuthServer is running and listening on port '+port);
  });


//Function to Validate Credential 
async function validateCredential(crdntl) {
  //Call Service to validate Credential received
  axios({
  method: 'get',
  url: 'https://.....',
  })
  .then(function(response) {
    ...check credential validation data
  })
  .catch(function (error) {
  console.log('ERROR: Unable to Validate Credential');
  //Unable to create Validate Credential so return error message for POST response
  return ('ERROR1');
  });
}

async function getToken(uid) {
  admin.auth().createCustomToken(uid)
    .then(function(customToken) {
    var AuthToken = customToken;
    var decoded = jwt.decode(AuthToken);
    console.log('Decoded Token: '+'\n',decoded);
    //Return Authorization Token for POST response
    return (AuthToken);
    })
    .catch(function(error) {
    console.log('ERROR: Unable to Create Custom Token', error);
    //Unable to create Token so return error message for POST response
    return ('ERROR2');
    });
  }
}

我需要返回 validateCredential 函数的结果,并将其结果传递给 getToken 函数并返回其结果,以便发送 POST 响应。我知道这些函数是异步的,我可以将它们与回调或承诺链接起来。

真正的问题是如何让 POST 响应等待来自 getToken 函数的回调,因为最终目标是将自定义令牌传递回 POST 响应正文中的移动应用程序。 任何帮助将不胜感激。

【问题讨论】:

标签: node.js asynchronous post asynccallback


【解决方案1】:

您的 validateCredentialgetToken 函数已经是 async 反过来返回承诺,要在 POST 函数中等待这些函数发送响应,您必须使 POST 函数 async 然后在调用这两个函数时使用await 关键字,当您使用await 函数执行时,会等待Promise 的函数响应解析,这是示例代码。

//Listen for app to POST Credential
app.post('/', async function(request, response) {
    console.log('Request Body: ',request.body);
    var Credential = request.body;

    //Validate Credential
    var userId = await validateCredential(Credential) //Waits until userId comes

    //Get Authorization Token
    var firebaseAuthToken = await getToken(userID) //waits until Token comes

    //Return Token for POST Response
    response.set('Content-Type','Text');
    response.end(firebaseAuthToken);
});

【讨论】:

  • 感谢您的快速回复。一旦我看到您的答案,这很明显,我感谢您的帮助。进行了更改,现在可以正常工作。再次感谢。
  • 它解决了问题,我标记为这样。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
相关资源
最近更新 更多