简体   繁体   English

Vue 2 API 以一种方法调用

[英]Vue 2 API calls in one method

I have two api calls I am making in a Vue method.我在 Vue 方法中有两个 api 调用。 I need to be able to set the api results into two variables and then call them in another method for manipulation.我需要能够将 api 结果设置为两个变量,然后以另一种方法调用它们进行操作。 How can this be done without using "Promise.all"不使用“Promise.all”如何做到这一点

currently I have this but the variables log "undefined"目前我有这个,但变量日志“未定义”

apiCall () {
    this.Loading = true;
    const resultOne = get('lots/path1', { locationId: '9047695746459876', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }).then((result) => {
        console.log(result, 'result 2')
      });
    const resultTwo = get('lots/path2', { locationId: '897349823749237', fromDate: moment(this.dateRange[0]).format('YYYY-MM-DD'), toDate: moment(this.dateRange[1]).format('YYYY-MM-DD') }).then((result) => {
        console.log(result, 'result 2')
      });
      console.log(resultOne, resultTwo) //returning undefined
      this.Loading = false;
  },

By using async/await .通过使用async/await

Edit: In this case they will be called in a sequence, the second one will be made after the first one is resolved (this is useful only in cases when you need data from the first req to make the second req).编辑:在这种情况下,它们将按顺序调用,第二个将在第一个被解决后生成(这仅在您需要来自第一个请求的数据来生成第二个请求的情况下才有用)。 If you want to make them in the same time you will have to use Promise.all() or Promise.allSettled() .如果您想同时制作它们,则必须使用Promise.all()Promise.allSettled()

Example:例子:

    async apiCall() {
        this.Loading = true;
        try {
          const resultOne = await get('lots/path1', { ... });
          console.log(resultOne);

          const resultTwo = await get('lots/path2', { ... });
          console.log(resultTwo);
        } catch (err) {
          console.error(err);
        } finally {
          this.Loading = false;
        }
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM