javascript - 在正常函数中获取错误未捕获的类型错误:p1() 未定义。如果...否则没有给出预期的输出
问题描述
function p1(){
let f = fetch("https://ghibliapi.herokuapp.com/people");
setTimeout(function(){
if(f.ok){
return f;
}
else{
return f.statusText;
}
},5000);
}
p1().then(function(data){
return data.json();
}).then(function(data){
console.log(data)
}).catch(function(error){
console.log("Error",error)
})
setTimeout(function(){
console.log("Stop")
},6000);
if else 在这种情况下不起作用,但是当我在 else 块之后放置 return f 时,它工作正常。为什么我不明白?
谢谢
解决方案
您还可以使用返回 fetch
function p1(){
fetch("https://ghibliapi.herokuapp.com/people").then(function(f){
if(f.ok){
return f.json();
}
else{
return f.statusText;
}
}).then(function(data){
console.log(data)
}).catch(function(error){
console.log("Error",error)
})
}
p1();