我正在研究Javascript,HTML和CSS项目。我想要的是使用其ID获得用户的名称。我使用fetch来做到这一点,但遇到了一些问题。
function getUserName(userId) {
let userTemp = window.API_HOST + '/users/' + userId;
return fetch(userTemp, {
headers: { authorization: localStorage.access_token },
})
.then(response => response.json())
.then(response => {
console.log('El nombre es: ' + response.name);
return response.name;
});
}
这里的问题是response.name是一个Promise对象,而不是实际名称。我尝试使用stringify,但是没有用。有什么建议吗?
编辑: 我需要在这样的地方调用该函数:
function showOffer(newOffer) {
if (newOffer.user_id === JSON.parse(localStorage.current_user)._id) {
const wrapper = document.createElement('div');
wrapper.className = 'wrap';
const prodHolder = document.getElementById('demo').appendChild(wrapper);
const offerBidderId = document.createElement('p');
const offerBidderIdText = document.createTextNode(
'Bidder id: ' + getUserName(newOffer.bidder_id),
);
console.log('New offer bidder id ' + newOffer.bidder_id);
offerBidderId.appendChild(offerBidderIdText);
wrapper.appendChild(offerBidderId);
....
}
也许是问题所在?
答案 0 :(得分:1)
200 - 600
始终返回fetch
。因此,您必须使用Promise
或then
来处理它。
您可以这样访问它:
async/await
或在异步函数中:
getUserName(1).then(name => {
console.log('El nombre es: ' + name);
});
关于异步功能的不错的文章:https://developers.google.com/web/fundamentals/primers/async-functions