Vue-渲染前异步/等待所有axios.get

时间:2020-03-04 02:11:04

标签: vue.js

在呈现HTML之前,是否可以在async内批处理await created()中的所有API调用?请参见下面的示例代码。

template.vue

  <template>
      <div v-if="isLoading> //insert skeleton loader </div>
      <div v-else> // insert HTML </div>
    </template>

    <script>
      async created() {
        this.IS_LOADING(true)

        await { 
        // all api calls
        this.functionA
        this.functionB
        }

        // then proceed to setTimeout to remove loading status
        setTimeout(() => {
          this.IS_LOADING(false);
        },2000)
      },

      computed: {
        ...mapState([
          'isLoading'
        ]),

      methods: {
        ...mapMutations([
          'IS_LOADING'
        ]),
        functionA() {}
        functionB() {}
    </script>

2 个答案:

答案 0 :(得分:1)

您可以输入2个await键,但是请确保功能A和B是Promise功能

有关更多信息:选中https://javascript.info/async-await

<script>
      async created() {
        this.IS_LOADING(true)

        let responseA = await this.functionA;
        let responseB = await this.functionB;

        // then proceed to setTimeout to remove loading status
        setTimeout(() => {
          this.IS_LOADING(false);
        },2000)
      },

      computed: {
        ...mapState([
          'isLoading'
        ]),

      methods: {
        ...mapMutations([
          'IS_LOADING'
        ]),
        functionA() {}
        functionB() {}
 </script>
 <template>
      <div v-if="isLoading>insert skeleton loader </div>
      <div v-else>insert HTML </div>
</template>

但是,以我自己的经验,将异步密钥放在created()前面会导致一些意外情况,我建议将它们全部包装在一个函数中并命名为

created(){
 this.getDataAndRender();
},

methods:{
 async getDataAndRender() {
  /// put your logic here

 }
}

答案 1 :(得分:1)

一个异步函数(例如:您的 async created(){} )可以包含一个await表达式,该表达式会暂停 执行异步功能以等待传递的Promise 解决方案,然后恢复异步函数的执行并评估 作为解析值。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

因此,以下方法可以解决您的问题:

  async created() {
    this.IS_LOADING(true)

    await this.functionA
    await this.functionB

    this.IS_LOADING(false);
  }

注意:functionA和functionB应该返回Promises

例如:

function resolveAfter2Seconds() {
  console.log("starting slow promise")
  return new Promise(resolve => {
    setTimeout(function() {
      resolve("slow")
      console.log("slow promise is done")
    }, 2000)
  })
}

function resolveAfter1Second() {
  console.log("starting fast promise")
  return new Promise(resolve => {
    setTimeout(function() {
      resolve("fast")
      console.log("fast promise is done")
    }, 1000)
  })
}

async function sequentialStart() {
  console.log('==SEQUENTIAL START==')

  // 1. Execution gets here almost instantly
  const slow = await resolveAfter2Seconds()
  console.log(slow) // 2. this runs 2 seconds after 1.

  const fast = await resolveAfter1Second()
  console.log(fast) // 3. this runs 3 seconds after 1.
}

sequentialStart()