As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center 指导。




8年前关闭。




node.js 中一个经常使用的异步函数调用习惯用法是使用这样的回调函数:
library.doSomething(params, function(err,result) {
    if (err) {
        ... handle error, retry etc
    } else {
        ... process results, be happy!
    }
});

这很棒 - 你调用一些东西,然后处理结果或错误。不幸的是,排除了第三个选项……您调用的代码永远不会执行您的回调。处理永远不会调用回调的可能性的最佳方法是什么?

很多时候,特别是如果你正在编写一个依赖网络的库,你需要保证你将调用传递给你的任何回调,并且只调用一次。考虑到这一点,像这样的模式看起来像要走的路:
// set a timout
var failed = false, callbackFailure = setTimeout(function() {
    ... handle failure, call further pending callbacks with a timeout error
    failed = true;
},30000);

library.doSomething(params, function(err,result) {
    if (!failed) {
        clearTimeout(callbackFailure);
        if (err) {
            ... handle error, retry etc
        } else {
            ... process results, be happy again!
        }
    }
});

您希望触发的任何回调实际上都会触发,这似乎是一个信念问题,而且我相信所有程序员都遇到过这样的情况,即无论出于何种原因,回调根本不会执行 - 宇宙射线、太阳黑子、网络故障、错误第三方库,或者……喘不过气……你自己代码中的错误。

像我的代码示例这样的东西实际上是采用的好做法还是 node.js 社区已经找到了更好的方法来处理它?

最佳答案

我不确定它去了哪里,但是这里突然出现了一个答案,并随着指向 https://github.com/andyet/paddle 的链接消失了 - 一个旨在提供回调执行“保险”的小型库。至少它表明我不是第一个在这个问题上挠头的人。

从文档上有一个轶事在某种程度上验证了这个问题:



他们给出的示例比我的示例稍微复杂一点,并且可以处理基于事件的回调,使代码能够在中间事件(如 ondata 处理程序触发)时定期“ checkin ”,然后在停止或超时时触发错误。

setTimeout(function() {
    paddle.stop();
}, 12000);

var req = http.get(options, function(res) {
    var http_insurance = paddle.insure(function(res) {
        console.log("The request never had body events!");
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
    }, 9, [res]);
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        http_insurance.check_in();
    });
});
req.end();

我在这里回答我自己的问题,但我仍然有兴趣看看是否存在任何其他实现、库或模式来解决相同的问题。

关于node.js - 在 node.js 编程中,如何处理回调不触发的场景?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12734712/

10-16 20:01