我不想问问题,但我觉得我需要知道如何做,或者更好的方法。我首先要说的是,我对 Javascript 很陌生,之前也学过 Java,对回调也很陌生。我读了一些其他问题,但仍然遇到一些困难。这实在是太可怕了。
在 rounds.js 中我有这个
exports.getCurrentRound = function(callback) {
exec(header + token + address, function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
rounds = stdout;
if (error !== null)
callback(null, err);
else
callback(null, currentRound);
});
}
在index.js中我有这个。
var result;
rounds.getCurrentRound( function (err, cr) {
currentRound = cr;
console.log("the current round is" + currentRound);
});
我怎样才能得到等于某物的结果?希望这是有道理的。请记住我正在运行 Windows。并且不愿意使用 promise 。不管那是什么。我希望我没有浪费您太多时间。
谢谢。
或者,如果有一种方法可以同步运行它,请告诉我它是什么。我只是想知道执行此操作的正确方法。
最佳答案
你就快到了!您已在顶部定义了结果,但现在只需设置它。
var result; // default: undefined
rounds.getCurrentRound( function (err, cr) {
currentRound = cr;
console.log("the current round is" + currentRound);
result = currentRound;
});
// result will be set at some point in the future
问题是您不知道何时会设置结果。您可以通过不断检查是否使用 setTimeout 设置来找出答案,但即使那也是异步的!
答案是您需要异步处理整个程序。谁需要结果就必须传入回调。
promise 只是表达“无论何时设置此变量,我都想要它的值”的一种方式。
var result = new Promise(function(resolve, reject){
rounds.getCurrentRound( function (err, cr) {
currentRound = cr;
console.log("the current round is" + currentRound);
resolve(currentRound); // set the actual value of result
});
});
// you can use the value of result later like this:
result.then(function(resultValue){
console.log('The result is ' + resultValue);
});
但请注意,即使如此,要使用结果的值,您仍然需要传递回调。它仍然是异步的!但您获得的好处是,您可以在代码中传递结果 promise ,并且一旦设置了值,其他代码就可以使用已解析的 promise 来执行某些操作。例如,假设您想在代码中的两个位置使用 result 的值...
result.then(function(resultValue){
console.log('My code is using result ' + resultValue);
});
// somewhere else
result.then(function(resultValue){
console.log('This other code is also using result ' + resultValue);
});
如果您使用的是最初开始使用的回调方法(在您的问题中),则需要使用结果值的两种情况都需要位于内部 回调。但使用 Promise,我们成功地将它们分开。
简而言之,答案是您必须稍微不同地思考您的代码,而不是将其视为一系列步骤,而尝试将其视为一系列可能按顺序发生但也可能发生的事件'每当他们完成时' - 异步。
关于javascript - 回调、导出和 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43200615/