链接延迟函数

Chaining the delay function

本文关键字:函数 延迟 链接      更新时间:2023-09-26

我想运行延迟函数作为下划线链的一部分。似乎延迟函数只能使用传递的显式参数 - 而不是包装器对象。此代码不起作用(未定义不是函数异常):

var message = function (text) {
                var txt = text;
                var show = function () { alert(txt); };
                return {
                    Text: txt,
                    Show: show
                };
            };
 _.chain(new message("hello")).delay(function(m) { m.Show(); }, 1000);

此代码有效:

var x = _.chain(new message("hello")).value();
            _.delay(function (m) { m.Show(); }, 1000, x);

有没有办法在较长的函数表达式中使延迟起作用?

例如,我想推迟视图模型实例的创建,然后将绑定到 UI 的延迟 X 毫秒。

chain()

下划线中所做的只是通过以下所有函数通过管道将其参数传递给这些函数,并将其作为第一个参数传递给这些函数。

由于delay()的第一个参数应该是一个函数,因此要实现您想要的功能,您必须执行以下操作:

_.chain(function(m) {
        m.Show();
    }).delay(1000, new message("hello"));

但我想它没有你想要的结构。

所以你不能直接使用delay(),但你可以通过tap()使用它:

_.chain(new message("hello"))
    .tap(function(m) {
        _.delay(function() {
            m.Show();
        }, 1000);
    })

甚至更简洁地使用tap()bind()

_.chain(new message("hello"))
    .tap(_.delay.bind(null, function(m) {
            m.Show();
    }, 1000))

如果您不想将集合传递给chain()并为集合的每个元素执行delay(),请使用 each() 而不是 tap()


以下不是答案,因为它使用 github.com/kriskowal/q 承诺而不是强调.js但这就是我认为您要做的,即通过一些异步的操作管道推送某些内容:

var message = function (text) {
                var txt = text;
                var show = function () { alert(txt); };
                return {
                    Text: txt,
                    Show: show
                };
            };

function delay(time) {
    return function(m) {
        var next = Q.defer();
        setTimeout(function() {
            next.resolve(m);
        }, 1000);
        return next.promise;
    }
}
Q.when(new message("hello"))
    .then(delay(1000))
    .then(function(m) {
        m.Show();
    });

_.delay 的第一个参数必须是一个函数,但如果消息类(对象),则 u 传递一个实例。F.E.

var foo = function(){
   console.log('FOO');
}
_.chain(foo).delay(200);

在您的情况下使用链条是开销。尝试这样的事情:

var showMsg = function(){
    var msg = new message("hello");
    msg.Show();
};
_(showMsg).delay(200);