Search code examples
node.jsasynchronouspostasynccallback

Async Processing for Node.js POST Request Response


I'm relatively new to Node.js and I'm creating a server that will accept a POST request from a mobile app whose body contains a credential that will then be verified via a GET to another server. If the GET response validates the credential, then the UID is extracted and a call is made to the firebase admin SDK to create a custom token. Here is a snippet of the code and two functions that are called to (a) validate the credential and (b) generate the custom token.

//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');
    });
  }
}

I need the result of the validateCredential function to be returned and its result passed to the getToken function and its result returned so that the POST response can be sent. I know these function are async and I can chain them with callbacks or promises.

The real issue is how to make the POST response wait for a callback from the getToken function as the ultimate goal is to pass the custom token back to the mobile app in the body of the POST response. Any help would be appreciated.


Solution

  • Your validateCredential and getToken functions are already async which in turn returns promise, To wait in POST function for these functions to send response, You have to make POST function async and then use await keyword while calling those 2 functions, when you use await function execution waits until function response which is Promise resolves, Here is sample code.

    //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);
    });