0

Main view:

<script>
import { testMethod1 } from "../helper";
export default {
  methods: {
    init(){
      console.log("Res:",  testMethod1());
    }
  }
}
</script>

Helper:

import DataService from "../services/data.service";
export  function testMethod1() {
    DataService.getByPage()
        .then((response) => {
            console.log(response)
          return response;
        })
      .catch((error) => {
        console.log(error);
     })
}

Output:

From view:

Res: undefined

From helper:

0: {_id: "60b621b4809e4304e04e7df4", desc: "aaa", …} 1: {_id: "60b621b4809e4304e04e7df5", desc: "bbb", …} (..)

What am I doing wrong?

Weronika
  • 368
  • 3
  • 24
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – DecPK Jun 04 '21 at 09:31
  • @decpk is right. your not actually returning a response from your `testMethod1` function. Try `return DataService.getByPage()...... blah...blah` – bassxzero Jun 04 '21 at 09:33

2 Answers2

1

// See this is the same error

const incorrectFoo = () => {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => json)
}



const correctFoo = () => {
 return fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => json)
}

const someOtherFoo = async () => {
 console.log('incorrect foo', await incorrectFoo(), 'correctFoo', await correctFoo())

}

someOtherFoo()

This method is executing a async call,

export  function testMethod1() {
    DataService.getByPage()
        .then((response) => {
            console.log(response)
          return response;
        })
      .catch((error) => {
        console.log(error);
     })
}

Now if you notice DatasService is a async call and that async call get to another context where it whenever get resolved returns response which mean testMethod1 is not returning anything any way try this

export  function testMethod1() {
    return DataService.getByPage()
        .then((response) => {
            console.log(response)
          return response;
        })
      .catch((error) => {
        console.log(error);
     })
}

<script>
import { testMethod1 } from "../helper";
export default {
  methods: {
    async init(){
      console.log("Res:",  await testMethod1());
    }
  }
}
</script>
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
0

After importing the method from helper, you need also to declare it in methods section like:

<script>
import { testMethod1 } from "../helper";
export default {
  methods: {
    testMethod1, // this is same with testMethod1: testMethod1,
    init(){
      console.log("Res:",  this.testMethod1());
    }
  }
}
</script>
LastM4N
  • 1,890
  • 1
  • 16
  • 22