使用 fetch api 向箭头函数添加隐式 return
Adding implicit return to arrow function using fetch api
我正在玩弄 promises 和 Javascript
中的 Fetch API
我想知道为什么当我不在我的 countryDetail()
函数中添加隐式 return 时,我得到未定义,而当我添加隐式 return 时我得到数据我在找什么?
这是没有隐式 return 的函数,其中 returns undefined
。
const countryDetail = (countryCode) => {
return fetch("http://restcountries.eu/rest/v2/all")
.then((response) => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("Unable to fetch data");
}
})
.then((data) => data.find((country) => country.alpha2Code === countryCode);
};
这里是使用箭头函数的隐式 return 相同的函数。此函数有效并且 return 数据而不是 undefined
const countryDetail = (countryCode) => {
return fetch("http://restcountries.eu/rest/v2/all")
.then((response) => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("Unable to fetch data");
}
})
.then((data) => {
return data.find((country) => country.alpha2Code === countryCode);
});
以下是函数在 app.js
中的使用方式
countryDetail("MX")
.then((country) => {
console.log(country.name);
})
.catch((err) => {
console.log(err);
});
看来,隐式代码中存在语法错误。缺少右括号。
.then((data) => data.find((country) => country.alpha2Code === countryCode);
应该是
.then((data) => data.find((country) => country.alpha2Code === countryCode));
我正在玩弄 promises 和 Javascript
Fetch API
我想知道为什么当我不在我的 countryDetail()
函数中添加隐式 return 时,我得到未定义,而当我添加隐式 return 时我得到数据我在找什么?
这是没有隐式 return 的函数,其中 returns undefined
。
const countryDetail = (countryCode) => {
return fetch("http://restcountries.eu/rest/v2/all")
.then((response) => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("Unable to fetch data");
}
})
.then((data) => data.find((country) => country.alpha2Code === countryCode);
};
这里是使用箭头函数的隐式 return 相同的函数。此函数有效并且 return 数据而不是 undefined
const countryDetail = (countryCode) => {
return fetch("http://restcountries.eu/rest/v2/all")
.then((response) => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("Unable to fetch data");
}
})
.then((data) => {
return data.find((country) => country.alpha2Code === countryCode);
});
以下是函数在 app.js
countryDetail("MX")
.then((country) => {
console.log(country.name);
})
.catch((err) => {
console.log(err);
});
看来,隐式代码中存在语法错误。缺少右括号。
.then((data) => data.find((country) => country.alpha2Code === countryCode);
应该是
.then((data) => data.find((country) => country.alpha2Code === countryCode));