[英]Promise object not returning a value
I am trying to get the value of asset
:我正在尝试获取
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?如何从请求中获取返回值?
You will need to use .then function.您将需要使用 .then 函数。
const asset = getAssetInformation(11002)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Using async
and await
is a practical way -使用
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 }
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.解包并使用 Promise 的方法是通过 .then() 函数,该函数将在 Promise 返回后运行。
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.这里的资产是一个承诺,你想在它上面使用一个 then 来获取值。
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.
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.