0

i am trying to break out of a for loop here on an error response and console the error message. Here is what i have tried

     var error = 0;
     var errorMsg;    
      for (let i = 0; i < this.fileArray.length; i++) {
          if ( this.fileArray[i] != undefined ) {
            if ( error == 0 ) {
              const fd = new FormData()
              fd.append('file', this.fileArray[i], this.fileArray[i].name)
              this.data.ImgUploader(fd).subscribe(
                res => {
                  if ( res['code'] != '00' ) { //error occurred. 1 is assigned to var error
                    error = 1
                    errorMsg = res['message']
                  } else {
                    error = 0
                  }
                }
              )
            } else {
              console.log(errorMsg)
              break;
            }
          }
        }

I am sending some image files via the ImgUploader function and recieving the response via the callback. I am trying to watch for errors via the error codes and assign 1 to the variable error. I expect variable error == 1 now but the code still enters into the code block where error == 0. Please where could i be going wrong. Thanks.

1

1 Answer 1

0

You are not able to break out from the loop in the callback passed to subscribe. The callbacks are called after the loop is finished.

JavaScript code runs on a single thread. That's why in your code snippet first all the loop iterations will be executed. Since the error has value 0 all the time, error == 0 will be true in all loop iterations. The callbacks of subscribe can be executed only after the loop is finished. At that time the value of error variable changes, but it does not make any difference because the loop is already finished.

If you want to know more what happens under the hood in the browser I recommend this talk: https://www.youtube.com/watch?v=8aGhZQkoFbQ

Sign up to request clarification or add additional context in comments.

Comments

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.