Javascript 等待回调,然后继续循环

Javascript 等待回调,然后继续循环,javascript,jquery,Javascript,Jquery,我有一个循环,我正在循环 我想创建一个自定义模式,并在继续之前等待响应 我怎样才能做到这一点?我知道我得等回电话 像这个例子: for(var x in array){ alert(x); console.log(x); } 这正是我想要的。但是我想要三个按钮。 但是警报不是javascript的一部分(?它在浏览器中。) 你们有什么想法吗 我在考虑这样做: var run = true; function foo(){

我有一个循环,我正在循环

我想创建一个自定义模式,并在继续之前等待响应

我怎样才能做到这一点?我知道我得等回电话

像这个例子:

 for(var x in array){
            alert(x);
            console.log(x);
        }
这正是我想要的。但是我想要三个按钮。 但是警报不是javascript的一部分(?它在浏览器中。)

你们有什么想法吗

我在考虑这样做:

var run = true;
function foo(){
    if (run){
        setTimeout(foo, 500);
    }
}

function stop(){
    run = false;
}

foo();
然后等待一个按钮点击的停止,然后继续。但这真的是一种好的做法吗

或者使用一个lambda函数作为customAlert的参数和一个“全局”变量,该变量保存我要处理的数组的当前位置,并使用函数执行此操作。Like:检查数组是否仍保留大于X的键。 然后再次执行该功能,每次增加全局X

感谢lostsource提供的代码: 哦,我有个主意;我将简单地在匿名函数中使用lostsource的解决方案,因此不获取全局变量。好极了

(function(){

})();

假设这是你的数组

var list = ['one','two','three'];
您可以尝试使用这种循环/回调方法

var x = 0;
var loopArray = function(arr) {
    customAlert(arr[x],function(){
        // set x to next item
        x++;

        // any more items in array? continue loop
        if(x < arr.length) {
            loopArray(arr);   
        }
    }); 
}

function customAlert(msg,callback) {
    // code to show your custom alert
    // in this case its just a console log
    console.log(msg);

    // do callback when ready
    callback();
}

jshiddle here:

MaggiQall,我知道你有一个答案,但我有一个灵活的解决方案,可能对你或其他人感兴趣

该解决方案依赖于jQuery(1.7+)和jQuery UI的
对话框
,但作为阵列原型的自定义方法实现,而不是作为jQuery插件实现

以下是数组方法:

Array.prototype.runDialogSequence = function(dialogCallback, startIndex, endIndex){
    startIndex = Math.max(0, startIndex || 0);
    endIndex = Math.min(this.length - 1, endIndex || this.length - 1);
    var sequenceIndex = 0,
        arr = this,
        dfrd = $.Deferred().resolve(startIndex);
    function makeCloseFn(seqData){
        return function(event, ui){
            if(seqData.continue_) { seqData.dfrd.resolve(seqData.arrayIndex+1, seqData); } //continue dialog sequence
            else { seqData.dfrd.reject(seqData.arrayIndex, seqData); } //break dialog sequence
        }
    }
    $.each(this, function(i){
        if(i < startIndex || i > endIndex) { return true; }//continue
        dfrd = dfrd.then(function(arrayIndex){
            var seqData = {
                dfrd: $.Deferred(),
                arrayIndex: arrayIndex,
                sequenceIndex: ++sequenceIndex,
                length: 1 + endIndex - startIndex,
                item: arr[arrayIndex],
                continue_: false
            };
            dialogCallback(seqData).on("dialogclose", makeCloseFn(seqData));
            return seqData.dfrd.promise();
        });
    });
    return dfrd.promise();
}
Array.runDialogSequence()
返回一个jQuery
promise
,允许在对话框序列完成(完成函数)或中途中断(失败函数)时执行自定义操作

以下是几个示例调用:

//Simplest possible
$("#myButton1").click(function(){
    myArray.runDialogSequence(openDialog);
});

//Call with custom startIndex and endIndex, and chanined `.then()` to provide custom actions on break/completion.
$("#myButton2").click(function(){
    myArray.runDialogSequence(openDialog, 1, 3).then(function(i, seqData){
        alert('All dialogs complete - last item = "' + seqData.item + '"');
    }, function(i, seqData){
        alert('Dialog sequence was broken at item ' + i + ' "' + seqData.item + '"');
    });
});


这是我想象中最接近通用的解决方案。

你是说你不能实际使用alert,因为它不支持足够的选项吗?不可能简单地替换
alert()
使用自定义模式,并使其执行与alert相同的方式。顺便说一句,alert是同步的。您将无法停止这样的函数执行-除非使用JS1.7的协同程序/但这不是非常跨浏览器的,并且需要在脚本类型上定义
版本
。您可能应该将
i
存储在一个执行上下文中,并将其传递给一个函数,该函数再对其进行一次迭代,从而调用样式化的警报,该警报再次将递增的
i
传递回迭代器函数。@Fabriciomattéi编辑了我的文章。你认为这是一种好的做法吗/+1.改进问题。是的,Lostsource的代码模板比我想象的还要整洁。是的,我也有这样一个想法(关于使用lambda函数):)非常感谢。非常有用,谢谢,太棒了,我刚刚使用了arr.lenght-1。实际上,如果回调必须异步执行任何操作,我认为这是行不通的。请检查一下,我想知道是否有解决方案,因为我正在尝试一个接一个地加载图像文件,每个文件都会花费一些时间:您只需要将回调放入成功返回或错误返回中。其思想是:“编写一个循环,它不会前进到数组中的下一个索引/项(如常规for循环)直到每个请求调用/完成其回调”。上面的例子非常简单但有效。谢谢@lostsourceThanks MaggiQall,看看将来是否有人觉得这个有用会很有趣。
function openDialog(seqData){
    /*
    seqData is an object with the following properties:
        dfrd: A Deferred object associated with the current dialog. Normally resolved by Array.runDialogSequence() to run through the sequence or rejected to break it, but can be resolved/rejected here to force the dialog sequence to continue/break. If resolved, then pass (seqData.arrayIndex+1, seqData), or custom values. If rejected, typically pass (seqData.arrayIndex, seqData).
        arrayIndex: The current array index.
        sequenceIndex: The current index within the sequence. Normally the same as arrayIndex but Differs when a non-zero startIndex is specified.
        length: The full length of the dialog sequence.
        item: The current item from the array.
        continue_: (false) Set to true to allow the sequence to continue.
    */
    var item = seqData.item;
    var $d = $("#d");
    $d.dialog({
        title: 'Dialog (' + seqData.sequenceIndex + ' of ' + seqData.length + ')',
        modal: true,
        buttons: {
            "Continue": function(){
                seqData.continue_ = true;//set to true before closing to go to next dialog.
                $(this).dialog("close");
            },
            "Cancel": function(){
                $(this).dialog('close');//closing with seqData.continue_ set to its default value false will break the dialog sequence.
            }
        }
    }).find("#message").text(item);//Typically you will do a lot more here to populate the dialog with item data.
    return $d;//openDialog() must return a dialog container, jQuery-wrapped.
}
//Simplest possible
$("#myButton1").click(function(){
    myArray.runDialogSequence(openDialog);
});

//Call with custom startIndex and endIndex, and chanined `.then()` to provide custom actions on break/completion.
$("#myButton2").click(function(){
    myArray.runDialogSequence(openDialog, 1, 3).then(function(i, seqData){
        alert('All dialogs complete - last item = "' + seqData.item + '"');
    }, function(i, seqData){
        alert('Dialog sequence was broken at item ' + i + ' "' + seqData.item + '"');
    });
});