2016-03-30 115 views
0

我有一個功能,拼寫檢查了一句:同步方法

let spellCheck = input => { 
    let corrected = []; 

    input.split(' ').map((word, index, array) => { 
     G.dictionary.spellSuggestions(word, (err, correct, suggestion, origWord) => { 
      correct ? corrected[index] = origWord : corrected[index] = suggestion[0]; 
     }); 
    }); 

    // terrible solution 
    Meteor._sleepForMs(200); 
    return ['SPELL', input, corrected]; 
}; 

這裏的問題是,之前修正陣列充滿了有詞的正確版本return語句發生拼寫錯誤。我可怕的解決方案是在返回語句之前調用睡眠函數,但我不能依賴它。

我已經看過使用Meteor.wrapAsync()的選項,但我不知道使用它的方法。我試着(天真地)使異步的spellCheck方法,但當然不起作用。

有沒有辦法讓G.dictionary.spellSuggestions方法本身同步呢?

+1

G.dictionary.spellSuggestions是一個異步函數。 你唯一的解決方案是讓spellCheck成爲一個異步函數。不要使用睡眠 – thangngoc89

+0

@ thangngoc89這將如何解決我的問題?這同樣適用於此,因爲即使spellCheck函數異步運行,更正後的列表仍然是空的。 –

+1

通過'異步'我的意思是回調,或承諾,或異步/等待。 – thangngoc89

回答

2

official Meteor docsMeteor.wrapAsync說:

總結,需要一個回調函數作爲其最後一個參數的函數。包裝函數回調的簽名應該是函數(錯誤,結果){}

最後一部分是關鍵。回撥必須具有確切的簽名function (error, result) {}。所以我會做的是,爲G.dictionary.spellSuggestions製作一個包裝,然後在該包裝上使用Meteor.wrapAsync。例如:

function spellSuggestions(word, callback) { 
    G.dictionary.spellSuggestions(word, (err, correct, suggestion, origWord) => { 
    callback(err, { correct, suggestion, origWord }); 
    }); 
} 

// This function is synchronous 
const spellSuggestionsSync = Meteor.wrapAsync(spellSuggestions); 

我在這裏做的基本上是將非錯誤結果打包到單個對象中。如果你要直接調用spellSuggestions(異步),它可能是這樣的:

spellSuggestions(word, function (error, result) { 
    if (!error) { 
    console.log('Got results:', result.correct, result.suggestion, result.origWord); 
    } 
}); 

所以現在在服務器端,您可以使用您的同步功能:

result = spellSuggestionsSync(word); 
+0

這不適合我。我收到一條錯誤消息,說err沒有被定義?我希望這個方法的文檔有幾個關於Meteor文檔的例子。 –

+0

糟糕,我的錯誤。我編輯了我的答案。 – ffxsam