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