代码之家  ›  专栏  ›  技术社区  ›  sofalse

Javascript-继续foreach

  •  -3
  • sofalse  · 技术社区  · 7 年前

    我有一段代码:

    var a = false;
    
    function wait(milliseconds, async) {
    if(!async) {
    setTimeout(function() {
            console.log('Sync timer done.');
            a = true;
            return true;
        }, milliseconds*1000);
    }
    (...)
    f_recipe.forEach(function(item, index) {
        if (obj['actual_step'] != 0 && obj['actual_step'] != index ) {
                e = "Desync";
            throw e;
        };
        console.log("Step: " + obj.actual_step);
        if(item.substr(item.length - 6) != "false)"){
            if (eval(item)) {
            obj['actual_step']++;
            }
        } else {
            eval(item);
            var ival = setInterval(function(){
                if(a) {
                    console.log('do the next thing');
                    clearInterval(ival);
                }
            }, 1000);
        }
    });
    

    如何让它工作?

    1 回复  |  直到 7 年前
        1
  •  0
  •   JLRishe    7 年前

    你试图做的似乎是一个非常糟糕的主意,但承诺可以帮助你做到这一点(在这里使用蓝鸟,因为它提供 Promise.delay Promise.each ):

    function wait(seconds, dontActuallyWait) {
      return dontActuallyWait ? null : Promise.delay(seconds * 1000);
    }
    
    function runSequence(things) {
      return Promise.each(things, function(thing) {
        return eval(thing);
      });
    }
    
    runSequence([
      'console.log("hello")',
      'wait(2, false)',
      'console.log("hello again")',
      'wait(5, false)',
      'console.log("goodbye")'
    ]);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.min.js"></script>