繁体   English   中英

承诺对象不返回值

[英]Promise object not returning a value

我正在尝试获取asset

const asset = getAssetInformation(11002);

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

console.log(asset);

结果是:

[object Promise]

如何从请求中获取返回值?

您将需要使用 .then 函数。

const asset = getAssetInformation(11002)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

使用asyncawait是一种实用的方法 -

 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 }

承诺返回另一个承诺。

解包并使用 Promise 的方法是通过 .then() 函数,该函数将在 Promise 返回后运行。

const asset = getAssetInformation(11002);

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

这里的资产是一个承诺,你想在它上面使用一个 then 来获取值。

代替..

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. 
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM