glog
glog

Reputation: 829

NodeJS - Nested async functions

in an express router .post which is async, I have this line:

var recaptcha = await tokenValidate(req);

tokenValidate is below:

async function tokenValidate(req) {
   
    // some code to generate a URL with a private key, public key, etc.
    
    return await tokenrequest(url);
  
}

Then tokenrequest is below: (note request is the npm request library)

async function tokenrequest(url) {
    request(url, function(err, response, body){
        //the body is the data that contains success message
        body = JSON.parse(body);
        
        //check if the validation failed
        if(body.success !== undefined && !body.success){
             return false;
          }
        
        //if passed response success message to client
         return true;
        
      })
}

Issue is the nested async functions. The initial recaptcha variable returns undefined since 'request' doesn't resolve, even though I'm using await. How can I get recaptcha to wait for tokenValidate which in turn has to wait for tokenrequest?

Thank you.

Upvotes: 0

Views: 626

Answers (2)

jfriend00
jfriend00

Reputation: 707158

Your tokenRequest() function is returning a promise (because it's async), but that promise resolves immediately with no value that is attached to your call to request(). And, the return values you do have are just returning to the request() callback where they are ignored, not from your actual top level function.

What I would suggest is that you ditch the request() module because it's deprecated and does not support promises and pick a new more modern module that does support promises. I use the got() module which would make this whole thing a LOT easier and a lot fewer lines of code.

const got = require('got');

async function tokenrequest(url) {
    let result = await got(url).json();
    return !!result.success;
}

Upvotes: 1

Kishan
Kishan

Reputation: 935

A couple issues:

  • Your tokenrequest function is not returning anything (the return value in the request callback function won't be returned)
  • await tokenrequest(url); won't work as you expect because the request library is using a callback (not async/await)

This can be fixed by returning a Promise:

async function tokenrequest(url) {
  return new Promise(function (resolve, reject) {
    request(url, function (err, response, body) {
      //the body is the data that contains success message
      body = JSON.parse(body);
        
      //check if the validation failed
      if (body.success !== undefined && !body.success) {
        resolve(false);
       
      } else {
        //if passed response success message to client
        resolve(true);
      }
    });
  });
}

Upvotes: 2

Related Questions