1

There is a function to generate a string and return it if it is in the User table.

 function generateFortToken(len) {
       let rs; 

        rs = randomstring.generate(len);
        User.findOne({where: {fort_token: rs}})
                .then(result => {
                    console.log("hit is : ", result);
                    if (!result) //need to return rs. but HOW?
                })
                .catch(err => {
                    console.log("Error search for fort token : ", err.message);
            });        

}

This generateFortToken is in module helper and is called from parent function like this:

user.fort_token = helper.generateFortToken(20);

This code does not work as many online posts pointed out since findOne returns a promise. But I am having hard time to rewrite it with callback to return the value of token generated.

user938363
  • 9,990
  • 38
  • 137
  • 303

2 Answers2

1

The code you came up with is fine, but it can be improved. In particular, you've fallen into to the Promise constructor antipattern. In short, you're constructing a new promise (await new Promise(next => User.findOne(...))) when you can use the promise returned by User.findOne directly:

async function generateFortToken(len) {
  for (let rs;; rs = randomstring.generate(len)) {
    try {
      if (await User.findOne({ where: { fort_token: rs }})) {
        return rs;
      }
    }
    catch (err) {
      console.log('Error search for fort token : ', err.message);
    }
  }
}
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • I was using `await` for findOne and somehow it didn't work for me. I didn't find an example of such online either. – user938363 Apr 26 '19 at 04:53
0

Solved the problem with the code below:

generateFortToken : async function(len) {
    let rs, bs, lp = true; 
    while (lp) {
        rs = randomstring.generate(len);
        await new Promise(next => {
            User.findOne({where : {fort_token : rs}})
                       .then(result => {
                            if(!result) lp = false;
                            next();
                       })
                       .catch(err => {
                            console.log("Error search for fort token : ", err.message);
                            //next();
                       });
        });

   }
   return rs;
},

In parent function:

user.fort_token = await helper.generateFortToken(20);

Inspired by Fernando Carvajal reply to the post.

user938363
  • 9,990
  • 38
  • 137
  • 303