我正在尝试从random-number-csprng API返回一个随机数,并将其发送到控制台,但不在模块外部。如何比较另一个模块内部模块的值?
我试图从.then()函数返回number参数,但是它仍然没有超出函数范围。
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,但似乎不会存储在Promise.try()
之外
答案 0 :(得分:0)
我看到您从字面上有点遵循他们文档中的示例代码。您需要从方法中返回promise,并通过await
对其进行异步使用:
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!');
}
}
}