Hi i am a newbie to Nodejs and i am trying to return an Object from an async function but promise returns undefined even though the data is fetched, can someone help please? Here is the code:
I am trying to return object from CreateRecoveryDoc function so you guys can ignore RegisterUser function since it just calls CreateRecoveryDoc function
index.js
async function CreateRecoveryDoc(u,userN,encat,urk){
const USEKEY = userN
const ENCAT = encat
u[USEKEY] = ENCAT
const data = db.get(ENCAT).put({
u
});
const noderesult = await db.get(urk).once(v =>{
const res = v
if (res === ''){
console.log("Failed to create a recovery doc")
}
else{
console.log("recovery doc created")
const Jsobject = {CAT:encat,URK:urk}
// console.log(Jsobject)
return Jsobject
}
});
}
exports.RegisterUser = async function RegisterUser(user,pass,email,HID){
var userN = user //giving username to userN variable
UserUAK = uuidv4()
console.log("UAK: " UserUAK)
const EIDD = String(HID.substring(process.env.cutfrom,process.env.to))
console.log(process.env.cutfrom)
console.log(process.env.to)
const ED = EIDD.replaceAll("-","")
console.log("EID: " ED)
const CATTOKEN = uuidv4()
const CAT = UserUAK CATTOKEN
console.log("CAT: " CAT)
const EDDfraze = ED
var encrypted = CryptoJS.AES.encrypt(CAT, EDDfraze);
console.log("Encryption: " encrypted.toString())
const encat = encrypted.toString()
const cred = await db.get(UserUAK).put({
username: user,
password: pass
})
const checkcred = await db.get(UserUAK).once(v =>{
U_res = v
if (U_res === ''){
console.log("Failed to create a User")
}
else{
console.log("Usercreated")
}
})
const URK = uuidv4() process.env.SECRET2
console.log("URK: " URK)
const defdata = await db.get(URK).put({
default: 'defaultID'
})
const data = await db.get(URK).once(v =>{
var u = v
CreateRecoveryDoc(u,userN,encat,URK)
});
}
Test.js
const Reg = require("./index.js")
var registres = Reg.RegisterUser("WS1DQWD","P@wdqwd","M123123s12","134832487623").then(x=>{console.log(x)})
console.log(registres) //logs undefined
CodePudding user response:
Well, the RegisterUser
function executes the actions and retrieves the data. What it doesn't do is return any value. This means it'll return a Promise by default, but this Promise won't have any value to resolve.
Depending on which object you want to have returned, you need to return it or create and return a new Promise from which you can call the resolve
-function.
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
CodePudding user response:
RegisterUser
needs to return the jsObect
value.
Try replacing the const data = ...
statement at the bottom of RegisterUser
with the following 3 statements:
let jsObject;
await db.get(URK).once(v =>{
var u = v
jsObject = CreateRecoveryDoc(u,userN,encat,URK)
});
return jsObject;
Alternatives may exist, but what .once
does and returns when called with a function as its argument is a secret (IMHO, after trying to search for it).