1

I am calling a parent function but my axios call after that is firing before the parent function finishes. Is there a way to use a Promise here so that the parent function resolves first before my axios post call is made?

let data = {
   name: "Charles"
   age:  44
}

this.$parent.updateInfo(data);

axios.post('/admin/setup/change', {
    status: "new",
    comment: this.newNotes,
})
raulInsto
  • 85
  • 11

2 Answers2

2

if $parent.updateInfo is asynchronous you can do something like that:

this.$parent.updateInfo(data)
  .then(() => {
    axios.post('/admin/setup/change', {
      status: "new",
      comment: this.newNotes,
    });
  })
  .catch(error => {
    console.log(error.message);
  })

Then you can be sure that axios.post will be called after $parent.updateInfo

Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51
  • interesting...inside `updateInfo` is an axios call. I can still use `then()` like that in the child? – raulInsto Jul 22 '20 at 20:45
  • `updateInfo` return Promise so you can use `.then` on this promise to handle the result of this promise. Read this it should help you to understand: - [What is promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) - [handling promise with .then](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) – Krzysztof Kaczyński Jul 22 '20 at 20:47
  • You can also use `await` which makes code more clear but then method in which you want to call this `await $parent.updateInfo` and `await axios.post` has to be asynchronous (`async`). [async & await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) – Krzysztof Kaczyński Jul 22 '20 at 20:50
1

You can use async/await, so the code will wait until execute further.

Btw i don't think this.$parent.updateInfo(data); is the common approach to trigger a function from the parent scope. I would prefer to emit an event to the parent instance, as suggested here https://stackoverflow.com/a/46208765/11377556

ProV
  • 251
  • 1
  • 4
  • 14