9

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

Flip
  • 6,233
  • 7
  • 46
  • 75
Hellhiem
  • 123
  • 1
  • 2
  • 7
  • A client to get the requested data must invoke the `async` function so s/he has to await for the response `async func() { [...] const data = await getRequestedData(requestAddress, params); // processing 'data' - js object .... }` – gvlax Sep 21 '18 at 11:47

5 Answers5

8

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
drew
  • 441
  • 3
  • 9
3

You have to return the data:

const response = await axios.get(requestAddress, {params: params})
return response.data;
hjrshng
  • 1,675
  • 3
  • 17
  • 30
2

One liner:

return (await axios.get(url)).data;
Victor
  • 349
  • 4
  • 7
0

In React component you can do with this trick:

function InitProduct() {
    // Get your product from database
    var productId = 'abc';
    axios.get('/api/products/' + productId).then(response => {
        $('.' + productId).text(response.data.ProductTitle);
    });

    return (<div className={productId}></div>)
}

export class TestNow extends Component {
    render() {
        return (
            <div>
                {InitProduct()}
            </div>
        )
    }
}
VnDevil
  • 1,321
  • 15
  • 13
0

An async function will always wrap what it returns in a promise so you should chain the caller with a then() method thereby resolving that promise for example: getRequestedData (requestAddress, params).then ( (data) => { ...do something... });

Or you could await the call to getRequestedData function, in which case the data inside the returned promise would be extracted for example:

let requestedData = await getRequestedData (requestAddress, params):
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Ediezzle
  • 1
  • 1