简体   繁体   中英

javascript callbacks in for loop

I have a for loop in a function in the structure

func(var, callback) {
    for(i = 0; i < len; i++) {
        validate(var, function(value) {
            if (!value) { callback(value) }
        }
    }
callback(true);
}

Where the function validate returns a boolean. I would only like to call my callback with true if it has not been called before. I tried putting a return after callback(value) but that didn't help.

Set a flag:

function func(foo, callback) {
    var called = false;
    for(var i = 0; i < len; i++) {
        validate(foo, function(value) {
            if (!value) {
                called = true;
                callback(value);
            }
        })
    }
    if (!called) {
        callback(true);
    }
}

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