1

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.

2
  • var as a variable name? and i is global. Commented Oct 28, 2014 at 18:20
  • That is correct for this example block of code. In my actual code I have meaningful variable names and my loop control is not a global variable. I just chose to use that name and not worry about the scope of i because it wasn't relevant to the question I was asking. Commented Oct 29, 2014 at 19:10

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's the only thought I had as well. I've done that and it is working. I'm not really sure why but the idea of setting a flag variable doesn't feel very clean to me. I guess it's because I'm fairly new to using callbacks and it feels like using a flag to avoid calling it multiple times seems like a very manual way of handling it, where I'm used to returning values so I haven't had to deal with this issue before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.