0

I'm new to Node JS and I'm having a hard time understanding callbacks and async functions,I went through a lot of documents and similar questions in here but it did not help me to figure out this. I hope someone can help me to figure this out and understand the issue. I need to return a value after a callback function is called. Here is my function:

 var result;
 var finalResult = authorize(JSON.parse(content), insertUsers); //Call the function here
     console.log("final result: ",finalResult);  //Promise { undefined }


 function authorize(credentials,callback) {
 const {client_secret, client_id, redirect_uris} = credentials.installed;
 const oauth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, async (err, token) => {
  if (err) return getNewToken(oauth2Client, callback);
  oauth2Client.credentials = JSON.parse(token);
  await callback(oauth2Client); //variable result gets value in callback func
  console.log("Result: ", result);  //result has value here
  return result;
} );

  return result;  //I want to return the result here but it's undefined!!!!
}


async function insertUsers(auth) {

const service = google.admin({version: 'directory_v1', auth});
var account = service.users.insert({
  "resource": {
    "name": {
      "familyName": lastName,
      "givenName": firstName
    },
    "password": "password",
    "primaryEmail": primaryEmail
  }
});

result = {
  "Email": (await account).data.primaryEmail 
};

 console.log ("result: ",result);
 return(result);
}
Atia
  • 3
  • 1
  • 5
  • Firstly, where is the result declared? the last return result will return undefined because fs.readFile will get executed asynchronosuly. – Vinayak Shenoy May 20 '20 at 19:57
  • Avoid passing an `async function` as a callback. Instead, promisify the callback-taking function. – Bergi May 20 '20 at 20:02
  • @VinayakShenoy result is a global variable, and gets value in the insertUsers function which is the callback function. I just added insertUsers function. – Atia May 20 '20 at 20:11
  • @Bergi can you explain more? I really have a hard time understanding this concept! – Atia May 21 '20 at 04:32

0 Answers0