-3

I am trying to get the value of asset:

const asset = getAssetInformation(11002);

function getAssetInformation(id) {
    return axios({
        method: 'GET',
        url: "/asset-information",
        params: {assetId: id}
    });
}

console.log(asset);

The result is:

[object Promise]

How do I get the returned value from the request?

AmazingDayToday
  • 3,724
  • 14
  • 35
  • 67
  • 5
    [Using promises - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) – Andreas Feb 06 '19 at 18:54
  • 1
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Feb 06 '19 at 19:01
  • @zero298 that is irrelevant here – Mulan Feb 06 '19 at 19:02
  • @user633183 I disagree. This is an issue with not understanding how to `Promise`, an asynchronous primitive. That question details how to use `Promise` in detail. – zero298 Feb 06 '19 at 19:03
  • @zero298 the asker is not trying to alter a variable - Sure, this is a very common mistake when dealing with asynchronous values, but it's not a mistake the asker is making here. – Mulan Feb 06 '19 at 19:05
  • @user633183 got it – tvankith Feb 06 '19 at 19:21

3 Answers3

0

You will need to use .then function.

const asset = getAssetInformation(11002)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Aditya Bhave
  • 998
  • 1
  • 5
  • 10
0

Using async and await is a practical way -

function axios(query) { // fake axios, for demo
  return new Promise (r =>
    setTimeout(r, 1000, { asset: query.params.assetId })
  )
}

function getAssetInformation(id) {
  return axios({
    method: 'GET',
    url: "/asset-information",
    params: {assetId: id}
  })
}

async function main() { // async
  const asset = await getAssetInformation (11022) // await
  console.log(asset)
}

main()
// 1 second later ...
// { asset: 11022 }
Mulan
  • 129,518
  • 31
  • 228
  • 259
-1

Promises return another promise.

The way to unpack and work with a promise is through the .then() function, which will run after the promise returns.

const asset = getAssetInformation(11002);

function getAssetInformation(id) {
    return axios({
        method: 'GET',
        url: "/asset-information",
        params: {assetId: id}
    });
}

Asset here is a promise, you want to use a then on it to get the value.

Instead of..

const asset = getAssetInformation(11002);

use

getAssetInformation(11002)
.then((response) => {
//What you returned will be here, use response.data to get your data out.

} )
.catch((err) => {
//if there is an error returned, put behavior here. 
})
Sam
  • 74
  • 1
  • 4