简体   繁体   中英

Javascript - continue foreach

I have a piece of code:

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

But when I get to 'do the next thing'(interval complete), the forEach loop doesn't continue to the next element of the array. 'a' is set to true after timeout (kind of a synchronous wait in JS). f_recipes is a string array with function call (eg 'wait(20, false)').

How to get it to work?

What you're trying to do seems like a very bad idea, but promises can help with this (using Bluebird here because it provides Promise.delay and 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM