我正在开发一个 Node.js 应用程序,我正在使用 Vorpal命令。我正在尝试将一个值从命令发送到一个函数,但我无法让它工作。我做错了什么吗?
代码如下:
vorpal
.command('rollto <num>', 'Rolls to')
.action(function(num) {
rollto(num);
});
function rollto(num) {
bettime = bettimems % 60;
socket.emit('betting', bettime);
timer1 = setInterval(function () {
bettime--;
socket.emit('betting', bettime);
if (bettime == 0) {
socket.emit('random number', num);
console.log("Rolled to:" + num + "!!!");
clearInterval(timer1);
}
}, 1000);
}
最佳答案
问题是您传递给命令的 action
的函数具有与您假设的不同的参数。
这是来自 docs 的相关部分:
.command.action(function)
This is the action execution function of a given command.
It passes in an arguments object and callback.
Actions are executed async and must either call the passed
callback upon completion or return a Promise.
这是一个工作示例:
var vorpal = require('vorpal')();
vorpal
.command('rollto <num>', 'Rolls to')
.action(function(arguments, callback) {
rollto(arguments, callback);
});
function rollto(arguments, callback) {
var num = arguments.num; // get 'num' parameter from arguments
timer1 = setInterval(function () {
console.log('test');
console.log(num);
clearInterval(timer1);
callback(); // Don't forget to use callback() to notify vorpal
}, 1000);
}
vorpal
.delimiter('myapp$')
.show();
请注意,您实际上在 setInterval 中有一个异步代码,因此您需要在最后使用 callback() 来通知 vorpal 处理已完成。
关于javascript - Vorpal.js 参数和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34777859/