1

I'm fetching api request via basic fetchSpecialityArray() function:

  fetchSpecialityArray(){
    this.$http.get('http://127.0.0.1:8000/api/speciality')
      .then(response => response.json())
      .then(result => this.specialityTest = result).then(this.checkSpeciality())
  },

then in checkSpeciality() method I'm checking if this request is complete:

  checkSpeciality(){
      console.log('check if complete and show array: ')
      console.log(this.specialityTest)
  },   

Unfortunately I've got empty array in my console. When I trigger fetchSpecialityArray() method again I've got correct response in console.

What is the cause of this behaviour and how should I correct my code to make this work?

2 Answers 2

3
then(this.checkSpeciality())

You are calling this.checkSpeciality immediately and then passing its return value (undefined because there is no return statement) to then().

You need to pass a function to then().

Since this.checkSpeciality makes use of this you need to capture the correct value of this too. You can use bind to create a function which will all checkSpeciality with the correct value of this.

.then(this.checkSpeciality.bind(this))
Sign up to request clarification or add additional context in comments.

4 Comments

thank you, your solution works, thank you also for an explanation. I was confused, also then(() => this.checkSpeciality()) works for me
I accepted Radonirina answer, because he was first and his solution also works, but your explanation is better. If I could I would accept both answers
my website shows he was first :) anyway. Your answer is also correct and I really appreciate your help!
This is the superior answer. It is complete with a why and how to fix. Being first is irrelevent if the answer is crap @gileneusz
1

Then require a function, here you pass a function that you invoke. You should invoke the function into the callback function as you can see int the following code:

.then(() => this.checkSpeciality())

Otherwise, you can pass the function without invoking it.

.then(this.checkSpeciality)

4 Comments

"Try this" — Why? This is entirely free of anything resembling an explanation.
then(this.checkSpeciality) — Won't that decouple the function from the correct this value and cause it to fail?
Update the answer @Quentin. Just trying to help him! :D
guys, thank you all for help :) I was almost giving this up, because today nothing works for me :)

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.