在哪里放置返回与node.js回调 [英] Where to put returns around callbacks with node.js

查看:82
本文介绍了在哪里放置返回与node.js回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一点背景;我使用node.js,并发现通过在异步代码中返回所有回调来避免许多错误。例如:

A little background; I work with node.js, and have found that many bugs are avoided by returning all callbacks in asynchronous code. For example:

function useMyAsyncFunc(stuff, c, callback)
    myAsyncFunc(stuff.a, stuff.b, c, function (error, data) {
        if (error) {
            return callback(error);
        }

        // Long body of code in here.

        return callback(null, data);
    });
}

我的问题是,考虑到以上情况会更好吗?回调链可能非常大,或者

My question is, would it be better to do the above, considering that the chain of callbacks could be quite large, or would

function useMyAsyncFunc(stuff, c, callback)
    myAsyncFunc(stuff.a, stuff.b, c, function (error, data) {
        if (error) {
           callback(error);
           return;
        }

        // Long body of code in here.

        callback(null, data);
        return;
    });
}

效率更高?

更明确地说,节点是否受益于后者,它被告知忽略回调函数的返回值?

Put more explicitly, does node benefit from the latter, where it is told to ignore the return value of the callback function?

推荐答案

我同样同意,一般来说,return callback()没有任何损害,也不会显着影响性能,而不是callback(); return;。我决定测试它与测试process.nextTick(... cb ...); return;。

I likewise agree that in general the "return callback()" does no harm nor does it significantly affect performance versus "callback(); return;". I decided to test that along with testing "process.nextTick(... cb ...); return;".

尝试以下代码:

'use strict';

var showComments = 0;
var counter = 10000;
var ab = process.argv[2];

function a(x, cb) {
    var myCB = function (err, result) { x = result; }

    x *= 1.01;
    if (showComments) console.log('start counter =', counter, ', x = ', x);

    if (--counter > 0) a(x, myCB);

    if (showComments) console.log("cb'ing");

    switch (ab) {
        case 'a':
            return cb(undefined, x);

        case 'b':
            cb(undefined, x);
            return;

        case 'c':
            process.nextTick(function () { cb(undefined, x); });
            return;

        default:
            console.log('Oops!  Try typing "node testReturnCallBack.js [a|b|c]"');
            process.exit(1);
    }
}

var start = (new Date()).getTime();

a(1, function (err, result) {
    console.log('final result = ', result);

    var finish = (new Date()).getTime();
    var diff = finish - start;
    console.log('run took %d milliseconds', diff);
});

你应该看到案例'a'和'b'多次运行基本上同时返回以毫秒为单位,而计算值保持不变。同时案例'c'的时间延长了约50%。

And you should see that cases 'a' and 'b' run multiple times return basically the same time in milliseconds while the computed value remains constant. Meanwhile case 'c' takes about 50% longer.

这篇关于在哪里放置返回与node.js回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆