简体   繁体   English

等待回调完成对性能有何影响?

[英]What are the performance implications of waiting for callbacks to finish?

I have been programming with Node.js for a little while, and I have found myself becoming increasingly annoyed with the need to chain callbacks. 我已经使用Node.js进行了一段时间编程,但发现自己对链接回调的需求越来越烦恼。 For example, when you need multiple models from a database as shown: 例如,当您需要从数据库中获取多个模型时,如下所示:

Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
    Schedule.findOne({'person_id': person.id }, 'events', function(err, schedule) {
        ...
    }
})

I am looking for solutions to this problem. 我正在寻找解决此问题的方法。 One idea I had was to do something like this: 我的一个想法是做这样的事情:

function() {
    var p;
    var s;
    var done = false;

    Person.findOne(..., ..., function(err, person) {
        p = person;
        done = true;
    });

    while(!done){}
    done = false;

    Schedule.findOne(..., ..., function(err, schedule) {
        s = schedule;
        done = true;
    });

    while(!done){}
    done = false;

    // ...
}

If I do my queries like this, what are the performance implications? 如果我这样查询,对性能有何影响? I'm also open to other ideas for solving this problem. 我也对解决此问题的其他想法持开放态度。

To answer your most direct question, the performance implication of spin-waiting for a callback is that the spin-wait may starve other, more useful tasks from being completed, either in the same process or on the same machine. 要回答您最直接的问题,旋转等待回调的性能含义是,旋转等待可能使同一过程或同一台计算机上无法完成的其他更有用的任务变得饥饿。 If your application were running on a single-user machine with no power management, this wouldn't matter, but neither of those things is likely. 如果您的应用程序在没有电源管理的单用户计算机上运行,​​则没关系,但这两种情况都不可能。 Busy-waiting will destroy battery life on mobile platforms, increase electricity costs in the datacenter, and make future maintainers of the code curse your name! 繁忙的等待将破坏移动平台上的电池寿命,增加数据中心的电力成本,并使将来的代码维护者诅咒您的名字!

As elclanrs already suggested in a comment, you could look at the " async " library to help streamline your code, but in any case you should avoid busy waiting. 正如Elclanrs在评论中所建议的那样,您可以查看“ async ”库以帮助简化代码,但无论如何都应避免忙于等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM