Hellhiem Hellhiem -3 years ago 630
Javascript Question

Why does Axios (with async/await) return a full promise?

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:

enter image description here

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download