promise - 承诺未决
问题描述
我正在尝试结合 fetch API 和 Promise
当我这样做时,一切正常
queryAPI(currency, cryptocurrency){
const url = fetch('https://api.coinmarketcap.com/v1/ticker/')
.then(response => response.json())
.then(data => console.log(data));
}
但是,当我尝试将其存储在变量中时,承诺一直处于未决状态
queryAPI(currency, cryptocurrency){
const url = fetch('https://api.coinmarketcap.com/v1/ticker/')
.then(response => {
const user = response.json()
console.log(user);
});
}
1)我做错了什么?
2)有什么方法可以在函数之外获取“用户”的值?
谢谢
解决方案
该.json
方法还返回一个承诺。您必须.then
再次调用才能获得最终结果:
queryAPI(currency, cryptocurrency){
const url = fetch('https://api.coinmarketcap.com/v1/ticker/')
.then(response => response.json())
.then(user => console.log(user))
}
因此您可以从该方法返回链式.then
squeryAPI
并在其余代码中使用它:
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)
});