0

In the file users.js I want to get code out of randomCode() to assign to the result and use it in whole endpoint '/login'.

randomCode.js

const crypto = require('crypto')

const randomCode = (callback) =>{
    crypto.randomInt(100000, 999999, (err, n) => {
        if (err) throw err;
        callback(n);
    });
}
    
module.exports = randomCode

users.js

require('dotenv').config()
const express = require('express')
const router = express.Router()
const randomCode = require('../controllers/randomCode')


router.get('/login', async (req, res, next)=>{
    try{
//-----------------------------------------------------
        randomCode((code) => {
          console.log(code,'code')
        })
//-----------------------------------------------------
        return res.send('ok')
    }
    catch(error){
        res.send(error)
    }
})

module.exports = router;

I tried to use await but whithout results.

router.get('/login', async (req, res, next)=>{
    try{
//------------------------------------------------------
        const result = await randomCode((code) => {
          console.log(code,'code')
        })
        console.log(result)
//------------------------------------------------------
        return res.send('ok')
    }
    catch(error){
        res.send(error)
    }
})
4
  • Why don't you just use randomCode as a helper method instead of a controller? crypto.randomInt won't ever throw an error, so you can skip the callback, just returning the code and using it like this: const code = randomCode(); However, I don't really see a problem with your code, what is the console printing? Commented Jan 15, 2022 at 19:25
  • 1
    The reason why I insert randomCode() in controller is: to find out :) I faced before with this kind of "problem" but usually I skipped it and moved function from controller to other location. Commented Jan 15, 2022 at 20:55
  • That's completely fair, good on you! I tried replicating that in a javascript file, and both functions seems to be working ok, so the problem must be somewhere else. What is the console.log printing your case? Commented Jan 15, 2022 at 21:41
  • Example app listening at localhost:8000-------- Database connected.------ undefined-------- 568350 code Commented Jan 15, 2022 at 21:50

1 Answer 1

1

There would be different approaches (especially as crypto.randomInt could be called synchronously), but I understand you are specifically interested in how to get a value from an asynchronous function, so I'll answer that:

const randomCode = function(){
  return new Promise((resolve, reject) => {
    crypto.randomInt(100000, 999999, (err, n) => {
      if( err ){
        reject( err );
      } else {
        resolve( n );
      }
    });
  });
}
router.get('/login', async (req, res, next)=>{
  try{
    const code = await randomCode();
    console.log(code)
    return res.send('ok')
  }
  catch(error){
    res.send(error)
  }
})

In cases where you can not change the randomCode() function for some reason, you need to wrap it into a Promise, like:

const randomCodePromise = function(){
    return new Promise((resolve, reject) => {
        randomCode((code) => {
            resolve( code );
        })
    });
}

(and obviously then use await randomCodePromise() instead of await randomCode())

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.