为什么第一个函数给我结果而第二个函数只给我未定义的结果?
Why the first funcion give me results and second one only undefined?
结果应该是一样的,但第二个函数给我未定义。
fetch("https://api.randomuser.me/?nat=US&results=1").then(res => res.json()).then(json => json.results).then(console.log).catch(console.error); // {user: xyz, ... }
const getFakePerson = async () => {
try {
let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
let {results} = res.json();
console.log(results);
} catch (error) {
console.error(error);
};
}
getFakePerson(); // Undefined
有人可以给我解释一下吗?
异步函数returns 总是一个承诺。 res.json()
还有
您需要 return
来解决 promise
,而不是像 resolve("some data")
那样解决 promise
const getFakePerson = async () => {
try {
let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
let { results } = await res.json();
return results;
} catch (error) {
};
}
getFakePerson().then(res => console.log(res))
更好的方法是:
const getFakePerson = async () => {
return fetch("https://api.randomuser.me/?nat=US&results=1")
.then(res => res.json())
.then(res => res.results)
}
getFakePerson()
.then(res => console.log(res))
你可以像这样工作
fetch("https://api.randomuser.me/?nat=US&results=1").then(res => res.json()).then(json => json.results).then(console.log).catch(console.error); //
const getFakePerson = async() => {
try {
let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
let json = await res.json();
let result = json.results;
console.log(result);
return result;
} catch (error) {
console.error(error);
};
}
console.log(getFakePerson());
结果应该是一样的,但第二个函数给我未定义。
fetch("https://api.randomuser.me/?nat=US&results=1").then(res => res.json()).then(json => json.results).then(console.log).catch(console.error); // {user: xyz, ... }
const getFakePerson = async () => {
try {
let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
let {results} = res.json();
console.log(results);
} catch (error) {
console.error(error);
};
}
getFakePerson(); // Undefined
有人可以给我解释一下吗?
异步函数returns 总是一个承诺。 res.json()
还有
您需要 return
来解决 promise
resolve("some data")
那样解决 promise
const getFakePerson = async () => {
try {
let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
let { results } = await res.json();
return results;
} catch (error) {
};
}
getFakePerson().then(res => console.log(res))
更好的方法是:
const getFakePerson = async () => {
return fetch("https://api.randomuser.me/?nat=US&results=1")
.then(res => res.json())
.then(res => res.results)
}
getFakePerson()
.then(res => console.log(res))
你可以像这样工作
fetch("https://api.randomuser.me/?nat=US&results=1").then(res => res.json()).then(json => json.results).then(console.log).catch(console.error); //
const getFakePerson = async() => {
try {
let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
let json = await res.json();
let result = json.results;
console.log(result);
return result;
} catch (error) {
console.error(error);
};
}
console.log(getFakePerson());