在继续循环之前等待回调

IT技术 javascript jquery
2021-03-21 19:13:48

我有一个循环遍历。

我想制作一个自定义模式并在继续之前等待响应。

我怎样才能做到这一点?我知道我必须等待回电。

像这个例子:

 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 的参数和一个“全局”变量,该变量保存我正在通过的数组的当前位置,并使用函数执行此操作。像:检查数组是否仍然持有大于 X 的键。然后再次执行该函数,每次增加全局 X。

谢谢你的代码:哦,我有个主意;我将在匿名函数中简单地使用 lostsource 的解决方案,因此我不会获得全局变量。优秀的。

(function(){

})();
2个回答

假设这是你的数组

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();
}

用法:

// start 'loop'
loopArray(list);

JSFiddle在这里:http : //jsfiddle.net/D9AXp/

这个想法是:“编写一个循环,在每个请求调用/完成其回调之前,不会前进到数组中的下一个索引/项目(如常规 for 循环)”。上面的例子非常简单而有效。谢谢@lostsource
2021-04-25 19:13:48
您只需要将回调放在成功返回或错误返回中。
2021-04-30 19:13:48
非常有帮助,谢谢,太棒了,我刚刚使用了 arr.lenght-1
2021-05-05 19:13:48
实际上,如果回调必须异步执行任何操作,我认为这不起作用。请检查一下,我很想知道是否有解决方案,因为我正在尝试一个一个加载图像文件,每个文件都需要一些时间:jsfiddle.net/evejweinberg/tydfbop6/1
2021-05-11 19:13:48
是的,我也有这样的想法(关于使用 lambda 函数):) 非常感谢。
2021-05-13 19:13:48

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

该解决方案依赖于 jQuery (1.7+) 和 jQuery UI's dialog,但作为 Array 原型的自定义方法实现,而不是作为 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() 依靠 :

  • 文档正文中的对话框模板,适合填充文本/值。
  • 包含按顺序填充对话框所需数据的类似项目(通常是 javascript 对象)的数组。
  • 传递一个正确构造的“openDialog”函数作为第一个参数。

这是一个带有解释性注释的示例“openDialog”函数:

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.
}

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 + '"');
    });
});

演示

这与我的想象所允许的通用解决方案非常接近。

感谢 MaggiQall,看看将来是否有人觉得这有用会很有趣。
2021-05-17 19:13:48