Node.js 如何从模块中获取值,返回未定义的值
我试图从随机数CSPRNGAPI返回一个随机数,它将值发送到控制台,但不在模块外部。如何比较另一个模块中模块的值 我试图从.then()函数返回number参数,但它仍然没有超出函数的范围Node.js 如何从模块中获取值,返回未定义的值,node.js,Node.js,我试图从随机数CSPRNGAPI返回一个随机数,它将值发送到控制台,但不在模块外部。如何比较另一个模块中模块的值 我试图从.then()函数返回number参数,但它仍然没有超出函数的范围 const Promise = require("bluebird"); const randInt = require("random-number-csprng"); class project { constructor(uname) { this.uname = uname;
const Promise = require("bluebird");
const randInt = require("random-number-csprng");
class project {
constructor(uname) {
this.uname = uname;
}
randomNumber(lowest, highest)
{
Promise.try(() => {
return randInt(lowest, highest);
}).then(number => {
console.log("Your random number:", number);
}).catch({code: "RandomGenerationError"}, err => {
console.log("Something went wrong!");
});
}
checkRandom()
{
console.log(`This is a test: ${this.randomNumber(1,100)}`);
if(this.randomNumber(1, 100) > 1)
{
console.log(`Works!`);
}
else
{
console.log(`Does not work!`);
}
}
}
输出
This is a test: undefined
Your random number: 65
Your random number: 71
我希望在未定义的日志上输出为65,但它似乎没有存储在
承诺之外。try()
我看到您在他们的文档中遵循了示例代码,有点过于字面。您需要从方法返回承诺,并通过以下方式异步使用它:
const randInt = require('random-number-csprng');
class Project {
constructor(uname) {
this.uname = uname;
}
randomNumber(lowest, highest) {
return randInt(lowest, highest);
}
async checkRandom() {
const randomValue = await this.randomNumber(1,100);
console.log(`This is a test: ${randomValue}`);
if (randomValue > 1) {
console.log('Works!');
} else {
console.log('Does not work!');
}
}
}