0

主视图:

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

帮手:

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

输出:

从视图:

回复:未定义

来自帮手:

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

我究竟做错了什么?

4

2 回答 2

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()

此方法正在执行异步调用,

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

现在,如果您注意到DatasService是一个异步调用,并且该异步调用会到达另一个上下文,只要解决它就会返回response,这意味着testMethod1不会以任何方式返回任何东西,试试这个

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>
于 2021-06-04T09:40:00.427 回答
0

从助手导入方法后,您还需要在方法部分中声明它,例如:

<script>
import { testMethod1 } from "../helper";
export default {
  methods: {
    testMethod1, // this is same with testMethod1: testMethod1,
    init(){
      console.log("Res:",  this.testMethod1());
    }
  }
}
</script>
于 2021-06-04T09:34:03.670 回答