【问题标题】:Wait for callback before continue for loop在继续循环之前等待回调
【发布时间】:2013-01-18 22:29:42
【问题描述】:

我正在循环一个 for 循环。

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

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

像这个例子:

 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 提供代码: 哦,我有个主意;我将简单地在匿名函数中使用 lostsource 的解决方案,所以我没有得到全局变量。太棒了。

(function(){

})();

【问题讨论】:

  • 你是说你实际上不能使用 alert 因为它不支持足够的选项?
  • 不可能简单地将alert() 替换为自定义模式并让它执行与警报相同的方式
  • alerts 是同步的 BTW。您将无法停止这样的函数执行 - 除非使用 JS1.7 的 coroutines/yield,但这不是跨浏览器,需要在您的脚本类型上定义 version。您可能应该将 i 存储在执行上下文中,并将其传递给一个函数,该函数使用它再进行一次迭代,该函数调用您的样式警报,该警报再次将递增的 i 传递回您的迭代器函数。
  • @FabrícioMatté 我编辑了我的帖子。你认为这是一个好习惯吗? ://
  • +1 用于改进问题。是的,Lostsource 的代码模板比我想象的还要整洁。

标签: javascript jquery


【解决方案1】:

假设这是你的数组

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/

【讨论】:

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

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

该解决方案依赖于 jQuery (1.7+) 和 jQuery UI 的 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”函数作为第一个参数传递。

这是一个带有解释性 cmets 的示例“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,允许在对话序列完成(done 函数)或在序列中间中断(fail 函数)时执行自定义操作。

这里有几个示例调用:

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

DEMO

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

【讨论】:

  • 感谢 MaggiQall,看看将来是否有人觉得这很有用会很有趣。
猜你喜欢
  • 2011-10-09
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 2021-12-26
  • 2020-05-19
  • 1970-01-01
相关资源
最近更新 更多