0

I have a function that returns a string but I can't seem to call this function and return a string no matter what export strategy I try. Everything returns undefined. ANy pointers or help would be greatly appreciated

In the below example i call the function with::

const generateUsername = require("../middlewares/generateUsername.js");

newUser.username = generateUsername;

function GenerateUnique() {
    let proposedUserName = generateUserName();
    //Works and returns a string "UNIQUEUSERNAME1223"   
 User.findOne({username: proposedUserName}).then((foundUserName) => {

        if (!foundUserName) {
            return proposedUserName;
        } else {
            GenerateUnique()
        }
    })
}

function generateUnique() {
    return new GenerateUnique();
}


module.exports = generateUnique()
bmarasc1
  • 3
  • 2
  • I'm not sure I understand. The way to export the function would be `module.exports = GenerateUnique`. There are other issues, however; like you're not returning the result of the recursive call and you're trying to use an async function in a non-async way, at the very least. – Dave Newton Oct 02 '20 at 15:10
  • It works, but throws a error ValidationError: User validation failed: username: Cast to string failed for value "GenerateUnique {}" at path "username" – bmarasc1 Oct 02 '20 at 15:19
  • It won't work if it finds a dupe. And it's still an async function, e.g., see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992). – Dave Newton Oct 02 '20 at 15:20
  • So silly it was the new in return new GenerateUnique(); Just needed return GenerateUnique(); Will fix the recursion and async call shortly thank you – bmarasc1 Oct 02 '20 at 15:27

1 Answers1

0

There are many things wrong with your approach. In short you can't do this because the function does not return anything. using return inside a then is simply a return value to the caller of the promise. The parent function will not return this value.

You can however refactor your code to something like this:

async function generateUnique() {
    let proposedUserName = generateUserName();
    let foundUserName = await User.findOne({username: proposedUserName});
    if (!foundUserName) return proposedUserName;
    return await generateUnique();
}


module.exports = generateUnique();

and when you import this module on other file:

const unique = require('yourmodulename').then(proposedUserName => {
   //you can access your proposed username from here
});

or export the function without calling it, import this function and await it's result inside an async function because you would be performing async operation when you create a new user.
more details here if you're interested.

Shahriar Shojib
  • 867
  • 8
  • 16