如何使用Axios Async Await使用Promise.all

Wil*_*ree 0 javascript promise vue.js nuxt.js

我在Nuxt.js中有此Axios Async Await代码,但不确定如何以及在何处放置Promise.all此代码。我试图向getThemes()and 承诺getData()。有人可以帮我提供Promise.all代码吗?

而且我必须把Promise.allmounted()

mounted() {
    this.getData(this.$route.params.id);
    this.getThemes();
  },

  methods: {
    async getThemes() {
      this.loading = true;
      await axios.get(`${process.env.API_URL}/v1/communication/email-themes`, {}).then((response) => {
        this.theme = response.data.data;
        this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;
        this.loading = false;
      }).catch((error) => {
        this.loading = false;
        this.errormsg = error.response.data.message;
      });
    },

    async getData(id) {
      this.loading = true;
      await axios
        .get(`${process.env.API_URL}/v1/communication/email-templates/${id}`)
        .then(({
          data
        }) => {
          this.templateName = data.data.name;
          this.templateCode = data.data.content;
          this.themeId = data.data.theme_id;
          this.loading = false;
        }).catch((error) => {
          this.loading = false;
          this.errormsg = error.response.data.message;
        });
    },

    async patchData(id) {
      await axios.put(`${process.env.API_URL}/v1/communication/email-templates/${this.$route.params.id}`, {
        name: this.templateName,
        content: this.templateCode,
        theme_id: this.selected
      }).then((response) => {
        this.results = response.data;
        this.loading = false;
      }).catch((error) => {
        this.loading = false;
        this.errormsg = error.response.data.message;
      });
    }
  }
Run Code Online (Sandbox Code Playgroud)

Vam*_*hna 6

一个 Promise,它将由async函数返回的值来解决,或者被async函数中引发的未捕获的异常拒绝。

参考- 异步功能

因此,您可以按照以下步骤进行操作

{
  mounted() {
    this.loading = true;
    Promise.all([this.getThemes(), this.getData(this.$route.params.id)])
      .then(values => {
        //first return value
        this.theme = values[0];
        this.selected = this.theme.filter(t => this.themeId === t.id)[0].id;
        //second return value
        this.templateName = values[1].name;
        this.templateCode = values[1].content;
        this.themeId = values[1].theme_id;

        this.loading = false;
      })
      .catch(error => {
        this.errormsg = error.response.data.message;
        this.loading = false;
      });
  },
  methods: {
    async getThemes() {
      const response = await axios.get(
        `${process.env.API_URL}/v1/communication/email-themes`,
        {}
      );
      return response.data.data;
    },
    async getData(id) {
      const response = await axios.get(
        `${process.env.API_URL}/v1/communication/email-templates/${id}`
      );

      return response.data.data;
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

然后使用Promise.all在数组中传递两个异步函数作为参数。