[英]API call leads to pending promise
I am attempting to store an API call response into the variable cat
.我正在尝试将 API 调用响应存储到变量
cat
中。 When I execute the following code, the console logs Promise { <pending> }
.当我执行以下代码时,控制台会记录
Promise { <pending> }
。 Why is this occuring?为什么会出现这种情况?
const got = require('got');
let dog = async () => {
try {
const response = await got('https://api.coinpaprika.com/v1/coins/btc-bitcoin');
return response;
} catch (error) {
console.log(error.response.body);
//=> 'Internal server error ...'
}
}
let cat = dog();
console.log(cat)
dog()
will return a promise because it is an async function. dog()
将返回 promise,因为它是异步 function。 You can get the value like that:你可以得到这样的值:
let cat = await dog();
OR或者
dog().then((cat)=>{
// do something here with the response
})
const got = require('got');
let dog = async () => {
try {
const response = await got('https://api.coinpaprika.com/v1/coins/btc-bitcoin');
return await response.json();
} catch (error) {
console.log(error.response.body);
//=> 'Internal server error ...'
}
}
let cat = dog();
console.log(cat)
In your code, response
is a promise.在您的代码中,
response
是 promise。 I expect your price data is being returned as JSON so you need to add return await response.json()
which will instead return a JSON object you can print out to the console.我预计您的价格数据将作为 JSON 返回,因此您需要添加
return await response.json()
,它将返回 JSON object 您可以打印到控制台。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.