Объект Promise не возвращает значение - PullRequest
0 голосов
/ 06 февраля 2019

Я пытаюсь получить значение asset:

const asset = getAssetInformation(11002);

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

console.log(asset);

Результат:

[object Promise]

Как получить возвращенное значение из запроса?

Ответы [ 3 ]

0 голосов
/ 06 февраля 2019

Обещания возвращают другое обещание.

Способ распаковки и работы с обещанием осуществляется с помощью функции .then (), которая запускается после возврата обещания.

const asset = getAssetInformation(11002);

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

Активом здесь является обещание, которое вы хотитеиспользуйте затем на него, чтобы получить значение.

Вместо ..

const asset = getAssetInformation(11002);

используйте

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. 
})
0 голосов
/ 06 февраля 2019

Использование async и await - практичный способ -

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 }
0 голосов
/ 06 февраля 2019

Вам нужно будет использовать функцию .then.

const asset = getAssetInformation(11002)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...