我正在尝试将提取API和Promise结合起来
当我这样做时,一切正常
queryAPI(currency, cryptocurrency){
const url = fetch('https://api.coinmarketcap.com/v1/ticker/')
.then(response => response.json())
.then(data => console.log(data));
}
但是,当我尝试将其存储在变量中时,promise会一直处于待处理状态
queryAPI(currency, cryptocurrency){
const url = fetch('https://api.coinmarketcap.com/v1/ticker/')
.then(response => {
const user = response.json()
console.log(user);
});
}
1)我在做什么错了?
2)有什么方法可以在函数之外获取“用户”的值?
谢谢
答案 0 :(得分:0)
.json
方法还返回一个promise。您必须再次致电.then
才能获得最终结果:
queryAPI(currency, cryptocurrency){
const url = fetch('https://api.coinmarketcap.com/v1/ticker/')
.then(response => response.json())
.then(user => console.log(user))
}
因此您可以从.then
方法返回链接的queryAPI
,并在其余代码中使用它:
const queryAPI = (currency, cryptocurrency) => {
return new Promise((resolve, rej) => {
return fetch('https://api.coinmarketcap.com/v1/ticker/')
.then(response => response.json())
.then(data => resolve({user: data, currency: 'EUR'}))
.catch(e => rej(e))
});
};
queryAPI('EU', 'bitcoin').then(data => {
console.log(data.user);
console.log(data.currency)
});