使用Javascript:如何实现的异步函数队列(无库) [英] Javascript: How to implement a queue of async functions (without libraries)

查看:179
本文介绍了使用Javascript:如何实现的异步函数队列(无库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找谷歌和SO,但我有一个很难包装我的大脑解决此出于某种原因。只是要强调,我不希望加载像jQuery库,因为我并不需要它的大部分。而我的可能的使用动画库,我已经建立了一些功能,我需要我自己(他们中的一些甚至没有标准的动画,你会在图书馆找到),所以我不确保这些甚至会很有帮助。其实,我可以很容易地所有权这个问题如何 - 异步函数队列,因为它不是具体到动画

在我的搜索,我已经跨越承诺的想法运行,但是,似乎是多一点比我更需要这个。

我得到的总的原则 - 你有一个使用的setInterval / setTimeout的异步函数,并给予合适的条件下,您清除的时间间隔(如适用),并运行一个回调:

 回调函数(){
    警报('这只是一个推销电话......现在我们说到哪儿了?');
}
功能动画(){
    变种I = 0,
        间隔=的setInterval(函数(){
            //做一些与我的当前值
            如果(我=== 100){
                clearInterval(间隔);
                回电话();
            }
            我++;
        },50);
}

当然,这如果你把它可重复使用,通过回调的动画参数()是更好的。然而,我真的希望能够做的是以下内容:

  VAR populateDialog =新的队列([
    {FN:动画,ARGS:['高度','300像素,1500]},
    {FN:类型,ARGS:[input.value,outputDiv]},
    {FN:亮点}
]);
populateDialog.start();

第一个函数将被调用,它的完成时,队列的数组中的下一个项目将被调用。问题是,当队列本身可以很容易地调用的函数,以,它需要知道当前函数的地位是继续之前完成。

我如何需要设计我要加入到队列中的任何功能,因此,它不是一个)公布其状态(我怎么都排队检测?)或b)可以接受来自队列的回调?我猜前者会涉及某种形式的自定义事件系统,而后者会更容易些,看是这样的:

 函数名(回调,参数1,参数2,... paramX){
    //的setTimeout或setInterval的一些东西,然后调用回调参数
}

,其中回调总是第一个参数,这样任何数目的其他参数可以上涨了。但就像我说的,我有真正的麻烦缠绕这一切我的大脑,所以详尽的解释/任何替代将是极大的AP preciated!

修改

这是我想出了可以在我的后续问题。


解决方案

  

我如何需要设计我要添加到队列中的任何功能,因此,它不是一个)公布其状态(我怎么都排队检测?)我猜它会涉及某种习俗事件系统


没错。

承诺的

这将是概念 - 动画函数返回一个对象上的队列可以将完成监听器。如果你不希望使用href=\"https://github.com/promises-aplus/promises-spec/blob/master/implementations.md\" rel=\"nofollow\">许多许多图书馆,你也可以实现自己的系统中(一次酒吧一个简单/子常常模式)。看看如何承诺/推迟库实现?(尤其是第一 两个一些灵感我的回答修订版)...

队列,然后将工作像

  VAR承诺=队列[I] .fn.apply(空,队列[I] .args);
promise.then(函数(){
    我++;
    // ...递归
});


  

b)在接受从队列回调?这将是更容易,看起来是这样的:
  函数名(回调,参数1,参数2,... paramX){...} 其中,回调总是第一个参数,从而使任何数量的其他参数可以上涨了


没错。或最后一个参数,这是更常见的。看一看的<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\"相对=nofollow> 适用函数法调用函数与参数的动态数字。

队列会是这样的。

 函数步骤(i){
    回调函数(){
        步骤(i + 1); //递归
    }
    如果(ⅰ&下; queue.length)
        排队[I] .fn.apply(空,排队[I] .args.concat(回调));
    //其他:全部完成
}


  

但就像我说的,我有真正的麻烦缠绕这一切我的大脑,所以详尽的解释/任何替代将是极大的AP preciated!


好吧,你已经钉了 - 有没有其他办法比你介绍的两种方法。诺方法更加健全,工程的动画功能的可变参数的参数更好的,而回调方法是比较简单的。

I have been searching Google and SO, but I am having a hard time wrapping my brain around this for some reason. Just to emphasize, I do NOT want to load a library like JQuery, since I don't need the majority of it. And while I could use an animation library, I've already built the few functions I need myself (some of them aren't even standard animations you would find in a library), so I'm not sure those would even be helpful. In fact, I could just as easily title this question "How to - Async function queue", since it isn't specific to animation.

In my searching, I have run across the idea of Promises, but that seems like a bit more than I need for this.

I get the general principle - you have an async function that uses setInterval / setTimeout, and given the right condition, you clear the interval (if applicable) and run a callback:

function callback() {
    alert('It was just a sales call... Now where were we?');
}
function anim() {
    var i = 0,
        interval = setInterval( function() {
            // do something with the current value of i
            if (i === 100) {
                clearInterval( interval );
                callback();
            }
            i++;
        }, 50);
}

Of course, this is better if you make it reusable, by making 'callback' an argument of anim(). However, what I truly want to be able to do is the following:

var populateDialog = new Queue([
    {fn: anim, args: ['height','300px',1500]},
    {fn: type, args: [input.value, outputDiv]},
    {fn: highlight}
]);
populateDialog.start();

The first function would be called, and when it's complete, the next item in the queue's array would be called. The problem is, while the queue itself could easily call the functions in order, it needs to know when the current function's status is 'complete' before proceeding.

How do I need to design any function I want to add to the queue so that it either a) publishes its state (and how do I have the queue detect that?) or b) can accept the callback from the queue? I'm guessing the former would involve some sort of custom event system, and that the latter would be easier, and look something like:

function name(callback, param1, param2, ... paramX) {
    // setTimeout or setInterval some stuff, then call the callback argument
}

where the callback is always the first parameter, so that any number of other parameters could be tacked on. But like I said, I am having real trouble wrapping my brain around all of this, so a thorough explanation / any alternatives would be greatly appreciated!

EDIT

The queue that I came up with can be found at my follow-up question.

解决方案

How do I need to design any function I want to add to the queue so that it either a) publishes its state (and how do I have the queue detect that?) I'm guessing it would involve some sort of custom event system

Exactly.

That would be the concept of Promises - your animation function returns an object on which the queue can attach the "done" listener. If you don't want to use one of the many many libraries, you can also implement your own system (a simple pub-once/sub-often pattern). Have a look at How is a promise/defer library implemented? (especially the first two revisions of my answer) for some inspiration…

The queue would then work like

var promise = queue[i].fn.apply(null, queue[i].args);
promise.then(function() {
    i++;
    // … "recurse"
});

b) can accept the callback from the queue? That would be easier, and look something like: function name(callback, param1, param2, ... paramX) {…} where the callback is always the first parameter, so that any number of other parameters could be tacked on.

Exactly. Or the last parameter, which is more common. Have a look at the apply Function method for calling functions with a dynamic number of arguments.

The queue would be something like

function step(i) {
    function callback() {
        step(i+1); // "recurse"
    }
    if (i < queue.length)
        queue[i].fn.apply(null, queue[i].args.concat(callback));
    // else: all done
}

But like I said, I am having real trouble wrapping my brain around all of this, so a thorough explanation / any alternatives would be greatly appreciated!

Well, you've nailed it already - there are no other alternatives than the two methods you outlined. The promise approach is more sound and works better for variadic parameters of the animation functions, while the callback approach is the simpler one.

这篇关于使用Javascript:如何实现的异步函数队列(无库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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