【问题标题】:How to manipulate an axios response and return a promise?如何操纵 axios 响应并返回一个承诺?
【发布时间】:2021-12-15 08:42:24
【问题描述】:

处理使用“axios”发出的async 请求的返回值并返回另一个Promise 的正确方法是什么?

这个:

return axios.get('/home.json')
    .then(({ data, ...res }) => 
        new Promise({
            data: data.json(),
            ...res
        })
    )

return new Promise(() => {
    const { data, ...res } = await axios.get('/home.json')
    return {
        data: data.json(),
        ...res
    }
})

...或者以上都不是?

【问题讨论】:

  • 以上都不是。您要解决的问题到底是什么? data.json() 没有真正意义,因为它不是 axios api 的一部分。您在两个示例中对 new Promise 的使用也不正确
  • @charlietfl 我想从端点异步获取数据,然后操纵请求的结果将其转换为 js 字典(与 fetch 的“.json()”一样)并返回该函数的也可以是一个 Promise。
  • 我对axios不熟悉,但是.then(async ({ data, ...res }) => ({ data: await data, ...res }))有用吗?

标签: javascript ecmascript-6 promise axios


【解决方案1】:

由于axios.get() 已经返回了一个promise,你可以在promise 链上构建并从链的末端返回你的最终值,它将成为整个promise 链的resolved 值并返回给调用者:

return axios.get('/home.json').then(data) => 
    // build whatever return value you want here and just return it
    // it will be the resolved value of the parent promise/chain
    // If you want to pack it into an object, you can do so here
    return {data: data};
});

如果您在解包数据和构建最终结果时需要一些其他异步操作,那么只需将该异步操作添加到上述承诺链(从链内返回一个承诺)。

附:我不明白你为什么这么想.then(({ data, ...res }) 是 axios 承诺结果的正确格式。从文档中我可以看出,事实并非如此。它使用一个值来解析,即请求的结果。另外,axios 没有.json()。它已经为您解析 JSON 结果(与 fetch() 不同)。

如果您希望它与 fetch() 一起工作,您必须单独读取和解析 json,您可以这样做:

return fetch('/home.json').then(response) => 
    return response.json();
}).then(result => {
    // create whatever final result value you want and return it
    return {data: result};
});

_

【讨论】:

    【解决方案2】:

    我觉得解决这个问题的最好方法是在 try-catch 块内使用 async-await 示例代码:

    const getApi = async() => {
    try{
    const {data, ...res} = await axios.get('/home.json')
    
    // this data is already in json usable format
    
    }catch(e){
      console.log('This error occurred',e)
    }
    }
    

    【讨论】:

    • axios() 不返回具有.json() 方法的结果。 OP问题的那部分是错误的。
    • 如果getApi() 失败,您不希望返回(承诺)undefined。只需省略 try 块并让它抛出(即拒绝)错误。
    猜你喜欢
    • 2019-07-30
    • 2019-01-26
    • 2015-11-27
    • 1970-01-01
    • 2019-11-17
    • 2015-06-05
    • 2016-11-28
    • 2019-08-27
    • 1970-01-01
    相关资源
    最近更新 更多