while循环中的Javascript回调不起作用? [英] Javascript callback within a while loop does not work?

查看:269
本文介绍了while循环中的Javascript回调不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在javascript中循环播放事件。本质上,它遍历值数组并在每次迭代期间进行查询。然后,根据查询的结果,它应该保持循环或停止并执行某些操作。

I'm trying to make an event driven while loop in javascript. Essentially it iterates through an array of values and makes a query during each iteration. Then, based on the result of the query it should either keep looping or stop and do something.

我意识到你不能在while循环中进行回调所以我我对如何实现这样的事情感到困惑。嵌套函数重复自身,这并不理想。

I realize that you can't have callbacks in a while loop so I'm confused on how to even implement such a thing. Nested functions repeat themselves and that's not ideal.

我的循环代码:

             var done = false;
             while(!done){
                bridgeCheckRooms(send,function(reply){ //callback
                    console.log(tagArray[count]);
                    console.log(reply);
                    if(reply.success){
                        done = true;
                    } else {
                        count--;
                    }
                });
            }


推荐答案

您应该使用递归。一种方法是这样的:

You should use recursion. An approach to that would be something like this:

     function next() {

            // ....

            bridgeCheckRooms(send,function(reply){ //callback
                console.log(tagArray[count]);
                console.log(reply);
                if(reply.success){
                    // continue() ?
                    // done = true;
                } else {
                    count--;
                    next();
                }
            });
     }

     next();

当然这只是一个例子。您应该根据整个代码对其进行调整。

Of course this is just an example. You should adapt it to you entire code.

这篇关于while循环中的Javascript回调不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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