我可以在关闭死亡/垃圾收集之前执行功能吗?

时间:2014-01-09 10:16:36

标签: javascript node.js

让我通过一个简单的例子来解释我的意思:

(function(){

    db.queryRows(function(row)
    {
        // some sophisticated async calls could present here
        request.write(row)
    })
    require('some-cool-module').onClosureDeath(function()
    {
        request.end('No more data for you.')
    })

})()

可以使用域名或其他东西吗?如果不是,这在理论上是否可行?

似乎我做了一个坏榜样,所以我写了另一个:

function getRandomInt(min, max)
{
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var server = require('http').createServer(function(request, response)
{
    var atEnd = function()
    {
        response.end('No more randoms for you.')
    };

    (function(){    

        response.statusCode = 200;
        response.setHeader('Content-Type','text/html; charset=UTF-8');

        // This loop is emulating a huge sophisticated complex async
        // callback delirium which cannot be easily understood and
        // tracked down, and I won't get paid for its refactoring.
        for(var i = 0;i < getRandomInt(0,getRandomInt(0,1000)); i++)
        {
            setTimeout(function()
            {
                response.write(String(getRandomInt(0,1000) + "<br/>"))
            },getRandomInt(0,30000))
        }

    //  What I'd wish to do:
    //  require('some-cool-module').onClosureDeath(atEnd)

    })()
}
).listen(11111);
console.log("Running @ http://127.0.0.1:11111")

1 个答案:

答案 0 :(得分:1)

(不是真正的答案,我只是不喜欢评论中的代码)

我认为这样的东西不会是回调意大利面。

function (callback) {
    function atEnd() {
        console.log('No more data');
        callback();
    }

    db.queryRows(function(row)
    {
        // some sophisticated async calls could present here
        request.write(row)
        atEnd();
    })
}

EDIT1: 我想你可以使用类似的东西(未经测试!)

function callback_hell(callback) //Your callback hell function
{
    setTimeout(function()
    {
        response.write(String(getRandomInt(0,1000) + "<br/>"));
        callback();
    },getRandomInt(0,30000))
}

function do_all(n, func, callback) { //This is just a wrapper for follow in fact
    var i = 0; //Counter of how many instance of follow have been started

    function follow() { //Wrapper of your callback hell (can be almost anything in fact, I use similar code for downloading files before using them
        if (i < n) { //If there is other instance to run
                callback_hell(follow);//Run it
                i = i + 1; //Increment the counter
        } else { //If all have been made
            console.log('end');
            callback();
        }
    }

    //What must be made before the loop
    response.statusCode = 200;
    response.setHeader('Content-Type','text/html; charset=UTF-8');
    //Start the loop
    follow();
}

do_all(getRandomInt(0, getRandomInt(0, 1000)), callback_hell, function () {
    request.end('No more data for you.');
    console.log('done?');
});