【问题标题】:How to use Promise.all using Axios Async Await如何使用 Promise.all 使用 Axios Async Await
【发布时间】:2018-12-26 00:57:24
【问题描述】:

我在 Nuxt.js 中有这个 Axios Async Await 代码,我不确定如何以及将 Promise.all 放在这里。我试图承诺getThemes()getData()。有人可以帮我处理Promise.all 代码吗?

我必须将Promise.all 放在mounted() 中吗?

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;
      });
    }
  }

【问题讨论】:

  • 我认为您在这里问的不止一件事,我的回答解决了您实际要问的问题,但也许您应该避免在getThemes()getData() 上设置this,而只需使用mounted() 中的 promise 的返回值。此外,您使用 await 很差,您不应该使用 thencatch,而是使用 try catch 块。
  • 代码中的另一个问题是,如果 getThemes()' and getData()` 都失败,其中一个将替换另一个 errormsg。使用 Promise.all 后,您可以捕获这两个错误并将它们连接起来。
  • 您好,感谢您的回复,您认为我应该替换所有方法吗?我对这个 Asnyc Await 很陌生,上面的代码不是我的,它是由我的同事制作的,我必须修复他的代码。
  • 您可以开始使用我的代码及其模拟的异步请求,如您所见,没有then。为了捕捉错误,你应该实现一个或多个 `try catch' 块。
  • 您也可以用您的 axios 调用替换 getPromise()getPromise(1) 将变为 axios.get(`${process.env.API_URL}/v1/communication/email-themes`, {})

标签: javascript vue.js promise nuxt.js


【解决方案1】:
here example how to wait axios all fetch
let url1="https://stackoverflow.com";
let url2="https://stackoverflow.com/questions";
let request1=axios.get(url1);
let request2=axios.get(url2);
let [answer1,answer2]=await axios.all([request1,request2]);
console.log(answer1.data);
console.log(answer2.data);

【讨论】:

    【解决方案2】:

    我想你想等待 getThemesgetData 完成:

       mounted() {
         this.loadData();
       },
       methods: {
         async loadData() {
           this.loading = true
           try {
             await Promise.all([this.getThemes(), this.getData(this.$route.params.id)])
           } catch (error) {
             this.errormsg = error.message;
           } finally {
             this.loading = false
           }
         }
        getThemes() {
           return 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;
           })
         },
    
        getData(id) {
           return 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;
             })
        },
      }
    

    【讨论】:

    • 感谢您的回复,看来这是这样做的方法,但我现在有另一个问题,有一个控制台错误指出“未捕获(承诺中)TypeError:无法读取属性'数据' _id.vue?e97a:100 处未定义的错误在“this.errormsg = error.response.data.message;”中在异步 loadData() 中。你能帮我多一点吗?
    • 我尝试了代码,有时它可以工作,但有时它会显示错误,就像我之前的代码一样。
    【解决方案3】:

    Promise 将被异步函数返回的值解析,或者被异步函数内抛出的未捕获异常拒绝。

    参考 - Async function

    所以你可以这样做

    {
      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;
        }
      }
    };
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2021-03-19
      • 2020-09-10
      • 2018-09-14
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多