【问题标题】:Mutiple Axios return not able to return the value but in cosole it is coming多个 Axios 返回无法返回值但在控制台中它即将到来
【发布时间】:2022-01-21 13:49:18
【问题描述】:

多个axios返回无法返回值但在控制台中它来了 第一个函数能够返回数据> 第二和第三不能做>

async getdata() {
  let url = `xxxxxxxx`;
  this.axiosConfig = {
    withCredentials: false,
    maxRedirects: 3
  };
  let config: AxiosRequestConfig = { ...this.axiosConfig
  };
  //axios.defaults.headers.common = { 'Authorization': 'Bearer ' + this.token }
  var result = await axios.get(url, config);
  console.log(result.data); // --------------> data is coming here
  return result.data; //------------>able to return the data from here
}
async getfame() {
  var res = await this.getdata()
  res.map(async(item: any) => {
    let url = `xxxxxxxx`;
    this.axiosConfig = {
      withCredentials: false,
      maxRedirects: 3
    };
    let config: AxiosRequestConfig = { ...this.axiosConfig
    };
    //axios.defaults.headers.common = { 'Authorization': 'Bearer ' + this.token }
    var result1 = await axios.get(url, config);
    console.log(result1.data); // -----------------> data coming here
    return result1.data; //------------> not able to return the data from here
    //return axios.get<string>(url, config);
  })
}
async getfix() {
  var res1 = await this.getdata()
  res1.map(async(item: any) => {
    let url = `xxxxxxxx`;
    this.axiosConfig = {
      withCredentials: false,
      maxRedirects: 3
    };
    let config: AxiosRequestConfig = { ...this.axiosConfig
    };
    //axios.defaults.headers.common = { 'Authorization': 'Bearer ' + this.token }
    var result2 = await axios.get(url, config);
    console.log(result2.data); // -----------------> data coming here
    return result2.data; //------------> not able to return the data from here
    //return axios.get<string>(url, config);   //-------------> tried this way but still not coming
  })
}

【问题讨论】:

    标签: javascript angular async-await axios


    【解决方案1】:

    在您的第二个和第三个函数中,您将在数组映射中返回这些 axios 调用。外部函数没有返回任何东西。

    如果您在每个 .map() 调用之前添加一个 return,那么这些函数将返回一个包含您预期结果的数组。

    async getfame() {
      var res = await this.getdata()
      return res.map(async(item: any) => {
        /* ... */
        return result1.data; 
      })
    }
    async getfix() {
      var res1 = await this.getdata()
      return res1.map(async(item: any) => {
        /* ... */
        return result2.data;
      })
    }
    

    【讨论】:

    • thx 它正在返回 promise 中的数据。你能告诉我如何通过 aysc 等待获取数据,因此它应该返回数据而不是 promise
    • Async/await 是语法糖,可以让 Promise 读起来像函数内的同步代码。它不会将承诺值转换为同步值。如果您有一个返回值的异步函数,则该响应将始终是一个承诺。
    • 我建议在过度依赖 async/await 之前研究 Promise 的核心基础。即使您以前这样做过,在基础知识上刷新自己总是一个好主意。
    猜你喜欢
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2019-02-09
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多