作者:hola'thrme | 来源:互联网 | 2023-02-06 06:03
我使用jsonplaceholder URL测试fetch API,但我的函数返回"Promise State:Pending",我不明白为什么:
function getUsers(url) {
return fetch(url)
}
const users = getUsers(`https://jsonplaceholder.typicode.com/users`);
users.then(respOnse=> {
console.log(response.text());
});
我认为问题是因为异步/同步方法?
1> T.J. Crowder..:
我认为问题变成异步/同步方法?
是.你(大部分)正确地消耗了原始的fetch()
承诺,但也返回了承诺.所以:text()
users.then(respOnse=> response.text()) // 1
.then(json => { // 2
console.log(json);
})
.catch(error => { // 3
// handle error
});
fetch("https://jsonplaceholder.typicode.com/users")
.then(respOnse=> response.text()) // 1
.then(json => { // 2
log("typeof json: " + typeof json);
log(json);
})
.catch(error => { // 3
// handle error
});
function log(msg) {
var p = document.createElement("pre");
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}