【问题标题】:how to use axios to capture http json response and pass value to another function?如何使用 axios 捕获 http json 响应并将值传递给另一个函数?
【发布时间】:2021-05-12 15:41:18
【问题描述】:

我正在尝试在 typescript 中对各种服务执行 GET 调用,并从它们的 json 响应中捕获一个值,该值将作为另一个函数中的参数传递。

通过一些在线搜索,我遇到了 axios,但我很难理解异步 API 以及如何处理 Promise。这是返回“未定义”作为输出的代码。

function getVersion(url: string) {
let version;
let res = await axios.get(url)
  .then((response: { data: { buildInfo: { details: { version: any; }; }; }; }) => {
    version = response.data.buildInfo.details.version;
    return version;
  })
  .catch((error: any) => {
    console.log(error);
  });
return version;

}

我也尝试过 async/await,但遇到了未处理的 Promise 问题。我不需要使用 axios,只要我可以访问响应以在后续函数中使用,任何库都可以。

【问题讨论】:

    标签: javascript typescript axios httprequest jsonresponse


    【解决方案1】:

    你可以为getVersion()返回一个承诺

    async function getVersion(url: string) {
      let res = await axios.get(url)
      .then((response: { data: { buildInfo: { details: { version: any; }; }; }; }) => {
        let version = response.data.buildInfo.details.version;
        return new Promise((resolutionFunc) => { // return a promise
           resolutionFunc(version);
        });
      })
      .catch((error: any) => {
        console.log(error);
      });
      return res;
    }
    
    getVersion(url).then(res => {console.log(res)})  // use 
    

    或者你可以直接返回 axios,因为 axios 会返回一个 promise

    async function getVersion(url: string) {
      let res = await axios.get(url)
      return res;
    }
    
    getVersion(url).then(res => {console.log(res)})  // use 
    

    【讨论】:

    • 我想从响应中检索 json version 值,因为我正在存储这个值。我将重复进行此调用,因为我将轮询版本值并检查存储的值。 axios能做到吗?我见过的例子涉及console.log,但我希望能够捕获json数据并将其用于其他功能并进行存储。
    • @Carolyn Aquino 我使用console.log来检查返回值的正确性,你可以对返回值做任何事情
    • 我以这种方式尝试了后一种方法: async function getVersion(url: string) { let res = await axios.get(url) return res; } ------------------------------------------------- ---------------- 让 myMap = new Map(); for (var i = 0; i { myMap.设置(端点[i].name,res.data.buildInfo.details.version);console.log(myMap);})}。我得到一个未处理的承诺警告
    猜你喜欢
    • 1970-01-01
    • 2019-08-06
    • 2018-09-18
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2021-01-12
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多