2015-02-24 61 views
1

我有下面的代碼在我興亞應用:更好地瞭解JavaScript的產生

exports.home = function *(next){ 
    yield save('bar') 
} 

var save = function(what){ 
    var response = redis.save('foo', what) 
    return response 
} 

,但我得到了以下錯誤:TypeError: You may only yield a function, promise, generator, array, or object, but the following object was passed: "OK"

現在,「OK」是從Redis的服務器,響應該說得通。但是我不能完全掌握髮電機這種功能的概念。任何幫助?

+0

哪些Redis的包您使用?我猜你正在使用普通的redis npm模塊,它需要回調。嘗試共同redis返回一個承諾。 – 2015-02-24 15:05:17

+0

哦,不,我正在使用coRedis,連接的代碼如下:var redis = require(「redis」), coRedis = require(「co-redis」), db = redis.createClient(), dbCo = coRedis(db); module.exports = dbCo;'(在一個單獨的文件中) – 2015-02-25 03:40:12

回答

1

你不屈服save('bar')因爲SAVE是同步的。 (?你確定你要使用保存)

因爲它是同步的,你應該改變這樣的:

exports.home = function *(next){ 
    yield save('bar') 
} 

這樣:

exports.home = function *(next){ 
    save('bar') 
} 

,直到它完成它會阻止執行。

幾乎所有其他的Redis方法都是異步的,所以你需要yield它們。

例如:

exports.home = function *(next){ 
    var result = yield redis.set('foo', 'bar') 
} 
+0

謝謝你的澄清。所以我不應該在這種情況下使用收益率?如果我想做'var res = get('foo'); this.body = res'?我也不需要通話的收益率嗎? – 2015-02-28 04:46:39

+0

您需要產生異步功能(這是Redis的大部分API)。我認爲'保存'是同步的(一種特殊情況)是令你困惑的。由於Redis的GET是異步的,因此您可以輸出它:'var res = yield redis.get('foo')'。我只知道redis.save是同步的,因爲它在文檔頁面上用粗體字表示:http://redis.io/commands/save。它有點像Node的'var text = fs.readFileSync('README.md')'(sync)與'fs.readFile('README.md',function(text){...})(異步)。這是否更有意義? – danneu 2015-02-28 20:49:51

0

產量應根據documentation在發電機功能內部使用。 其目的是返回要在下一次迭代中使用的迭代結果。

就像這個例子(從資料爲準):

function* foo(){ 
    var index = 0; 
    while (index <= 2) // when index reaches 3, 
        // yield's done will be true 
        // and its value will be undefined; 
    yield index++; 
} 

var iterator = foo(); 
console.log(iterator.next()); // { value:0, done:false } 
console.log(iterator.next()); // { value:1, done:false } 
console.log(iterator.next()); // { value:2, done:false } 
console.log(iterator.next()); // { value:undefined, done:true } 
+0

感謝您的答案。函數調用實際上是在一個生成器函數中,只是忘了寫它。請檢查我的編輯。 – 2015-02-24 08:07:44