Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 260
Hellhiem Avatar asked Jul 07 '17 12:07

Hellhiem


2 Answers

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
like image 66
drew Avatar answered Oct 13 '22 05:10

drew


You have to return the data:

const response = await axios.get(requestAddress, {params: params})
return response.data;
like image 36
hjrshng Avatar answered Oct 13 '22 04:10

hjrshng