[英]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'
.在文件 users.js 中,我想从randomCode()
中获取code
以分配给result
并在整个端点'/login'
中使用它。
randomCode.js随机代码.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用户.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.我尝试使用await
但没有结果。
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)
}
})
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:会有不同的方法(尤其是可以同步调用crypto.randomInt
),但我知道您对如何从异步 function 获取值特别感兴趣,所以我会回答:
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:如果由于某种原因无法更改randomCode()
function,则需要将其包装到 Promise 中,例如:
const randomCodePromise = function(){
return new Promise((resolve, reject) => {
randomCode((code) => {
resolve( code );
})
});
}
(and obviously then use await randomCodePromise()
instead of await randomCode()
) (显然然后使用await randomCodePromise()
而不是await randomCode()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.