0

What is the correct way to manipulate the return value of a async request made with "axios" and return another Promise?

This one:

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

or

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

...or none of the above?

Giuseppe
  • 531
  • 1
  • 5
  • 19
  • None of the above. What exactly is the problem you are trying to solve? `data.json()` doesn't really make sense as that isn't part of the axios api. Your use of new Promise in both examples is incorrect also – charlietfl Oct 31 '21 at 00:02
  • @charlietfl I want to get data from an endpoint asynchronously, after which manipulate the result of the request to translate it into a js dictionary (as with fetch's ".json()") and have the return of that function also be a Promise. – Giuseppe Oct 31 '21 at 00:07
  • I’m not familiar with axios, but does `.then(async ({ data, ...res }) => ({ data: await data, ...res }))` work? – Ry- Oct 31 '21 at 00:10
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) and [never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Oct 31 '21 at 02:00

2 Answers2

3

Since axios.get() already returns a promise, you can just build on the promise chain and return your eventual value from the end of the chain and it will become the resolved value of the whole promise chain that will go back to the caller:

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

If you need some other asynchronous operation in unpacking the data and building your final result, then just add that asynchronous operation to the above promise chain (returning a promise from inside the chain).

P.S. I don't understand why you're thinking that .then(({ data, ...res }) is the proper format for an axios promise result. As best I can tell from the documentation, it is not. It resolves with one value, the result of the request. Plus, there is no .json() with axios. It already parses JSON results for you (unlike fetch()).

If you wanted this to work with fetch() where you do have to separately read and parse the json, you could do this:

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

_

jfriend00
  • 683,504
  • 96
  • 985
  • 979
-1

I feel the best way to go about this is using async-await inside a try-catch block Sample code :

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)
}
}
Ankit Sanghvi
  • 467
  • 5
  • 18
  • `axios()` does not return a result that has a `.json()` method. That part of the OP's question is just wrong. – jfriend00 Oct 31 '21 at 00:53
  • You don't want `getApi()` return (a promise for) `undefined` if it fails. Just omit the `try` block and let it throw (i.e. reject with) the error. – Bergi Oct 31 '21 at 02:01