Promise returns undefined nodejs

450 views Asked by At

i am back with a same issue for my promise returning undefined please help.

Here, i am using ipfs to save data with savedata() which takes in a json string,a document name and a secret phrase.

i am not quit sure why promise is returning undefined i have checked everything

here is the new code

index.js

 exports.savedata = async function savedata(jsondata,Docname,secretuuid){
    const docname = Docname
    let ipfss = await main();
    let datavar = await ipfss.add(jsondata);

    //check if input file exists or not?
    const fpath =  __dirname + "\\"+ "input.json"

    if (fs.existsSync(fpath)) {
    }

    else{
        const defobj = {defaultID:"defaultID"}
        fs.writeFile("input.json",JSON.stringify(defobj),function(err){
            // console.log('saved!') 
        })
    }

    //create an object and put an array with defaultid:defaultid to it
 

    //take that object and keep concatenating the new arrays[new documents]
    fs.readFile("input.json","utf-8",function(err,data){
        if(err){
            console.log(err)
        }
     
        const rembrk1 = data.replaceAll("{","")
        const rembrk2 = rembrk1.replaceAll("}","")
        const newstring = JSON.stringify({[docname]: datavar.path})
        const URK = uuidv4() + "rkbyavds"
        const CAT = CryptoJS.AES.encrypt(String(datavar.path),secretuuid);
        var ENCAT = CAT.toString()
        const fstring = "{" + rembrk2 + "," + docname + ":" + CAT  + "}"
        fs.writeFile("input.json", JSON.stringify(fstring),function(err){
            if(err){
                console.log(err)
            }
        })
        
        return new Promise((resolve,reject) => {
            // console.log('saved')
            const retobj = {CAT:ENCAT,URK:URK}
            resolve(retobj)
        });
             
        
    })

}

test.js


obj = JSON.stringify({user:"MqwMedz2edemusaaa",age:1291})
const op = savedata(obj,"doc1","verysecretuuid")
op.then(x=>{
    console.log(x)
})
1

There are 1 answers

0
timlg07 On

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