2016-07-08 51 views
1

我是node.js的新手,我正在開發一個代碼庫,通過將調用包裝到生成器函數中來利用co庫。一個簡化的例子是這樣的:co node.js庫的用途是什麼?

module.exports.gatherData = function*() 
{ 
    // let img = //get the 1 pixel image from somewhere 
    // this.type = "image/gif"; 
    // this.body = img; 

    co(saveData(this.query)); 
    return; 

};

function *saveData(query) 
{ 
    if(query.sid && query.url) 
    { 
     // save the data 
    } 
} 

所以我去了共同的主頁在GitHub和描述說:

「發電機基於控制流善良的NodeJS和瀏覽器,使用的承諾,讓你寫一個無阻塞碼好的方式。「

在node.js的上下文中,這段代碼不會是非阻塞的嗎?

yield saveData(this.query) 
+0

*這是不是代碼無阻塞太node.js的背景下? *號迭代器和發生器是同步操作。 * co *庫使用生成器語法來包裝承諾,使異步代碼看起來像是以同步方式編寫的。 'yield saveData'會產生一個未解決的Promise – CodingIntrigue

+0

實際上'co(saveData(this.query));'生成器內部確實是垃圾。 – Bergi

+0

爲什麼垃圾?你能詳細說明一下嗎? –

回答

3

沒有關於發電機功能的阻塞/非阻塞。它們只是表達可中斷控制流的工具。

流程中斷的方式只能由發生器的調用者來決定,在這種情況下,該庫會在產生異步值時等待異步值。有很多方法對皮膚此貓co

  • module.exports.gatherData = co.coroutine(function*() { 
        … 
        yield saveData(this.query)); 
    }); 
    var saveData = co.coroutine(function* (query) { 
        if(query.sid && query.url) { 
         // save the data 
        } 
    }); 
    
  • module.exports.gatherData = co.coroutine(function*() { 
        … 
        yield co(saveData(this.query)); 
    }); 
    function *saveData(query) { 
        if(query.sid && query.url) { 
         // save the data 
        } 
    } 
    
  • module.exports.gatherData = co.coroutine(function*() { 
        … 
        yield* saveData(this.query)); 
    }); 
    function *saveData(query) { 
        if(query.sid && query.url) { 
         // save the data 
        } 
    }