node generator 模仿co

 

exports.run = function(fn ){
    return function(onDone){
        function thunk(tfn , ctx){
            return function(sql , id){
                var args = Array.prototype.slice.call(arguments , 0)
                args.push(cbk)
                tfn.apply(ctx , args)
            }

        }

        function cbk(err , result) {
            if (err) return onDone(err)
            next(result)
        }

        function next(resultPre){
            var cur = generator.next(resultPre)
            if (cur.done) onDone(null , cur.value)
        }

        var generator = fn(thunk)
        next()
    }
}

 

 

        octopus.run(function *(thunky){
            var mysql = require('mysql');
            var connection = mysql.createConnection(config.db.mysql.slave())
            connection.connect()
            var sql = 'select * from table'

            var query = thunky(connection.query , connection)  //這裏封住函數 以便添加cbk到參數最後
            var row = yield query(sql , [])//經過cbk調用 generate的next(val)方法將val傳給row 一切都是異步的 只是看起來像同步
           
            connection.end()
            return row


        })(function (err , result){
            console.log('err' ,err)
            console.log('result' , result)
        })
相關文章
相關標籤/搜索