2017-04-04 27 views
1

我不喜歡問一個問題,但我覺得我需要知道如何,或更好的方式來做到這一點。我應該首先說我是Javascript的新手,之前完成了Java,並且對回調也是新手。我讀了其他一些問題,但仍然有一些困難。這真是太可怕了。回調,出口和javascript

在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。我不願意使用承諾。無論如何。我希望我不會浪費你太多時間。

謝謝。

或者,如果有一種方法可以同步運行,請告訴我它是什麼。我只想知道這樣做的正確方法。

+0

正確的方法是隻提到回調內的結果 – Alnitak

回答

0

你快到了!您已經在頂部定義了結果,但您現在只需要設置它。

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來設置它,但即使是異步的!

答案是你需要對待你的整個程序異步。無論誰需要結果,都必須通過回調。

承諾只是一種說法'我想要這個變量的值,只要它設置了'。

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); 
}); 

但請注意,即使如此,要使用結果的值仍需要傳遞迴調。這是還是異步!但是,您獲得的好處是您可以在代碼中傳遞結果諾言,而其他位代碼可以使用已解決的諾言在設置值後執行某些操作。舉例來說,假設你想使用結果的值在代碼兩個地方......

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); 
}); 

如果你使用,你首先開始了回調方法(你的問題),這兩個你需要使用的值的結果需要裏面的的回調。但是使用承諾,我們設法將它們分開。

簡而言之,答案是您必須稍微改變想法,而不是將其視爲一系列步驟,嘗試將其視爲一系列可能發生的事件,但也可能發生'每當他們完成' - 異步。

+0

我真的很感謝你的回答。我想我會嘗試使用承諾。但是當你說任何需要結果的人都必須通過回調。你能舉個例子嗎? –

+0

我已經添加了一個例子:) – meltuhamy