Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
Get variable out from function which is calling export.modules node.js

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)
    }
})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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())

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda