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?
// 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>