Why does Axios (with async/await) return a full promise?
19,021
Solution 1
Like Ha Ja said, I think you still need to resolve the promise. If you just return the await you're going to get a promise.
const fs = require ('fs')
function getText () {
return new Promise( (resolve, reject) => {
fs.readFile('./foo.txt', 'utf8', (err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
}
async function output () {
try {
let result = await getText()
console.log("inside try: ", result)
return result
}
catch (err){
console.log(err)
}
}
console.log("outside: ", output())
output().then( result => console.log("after then: ", result))
// outside: Promise { <pending> }
// inside try: foo text
// inside try: foo text
// after then: foo text
Solution 2
You have to return the data:
const response = await axios.get(requestAddress, {params: params})
return response.data;
Solution 3
One liner:
return (await axios.get(url)).data;
Author by
Hellhiem
Updated on June 27, 2022Comments
-
Hellhiem almost 2 years
I have a problem with
async
/await
. Here is my code:import axios from 'axios' export default async function getRequestedData (requestAddress, params) { return await axios.get(requestAddress, {params: params}) }
But instead of the result it returns a full promise, so the data is heavily nested inside a promise: