Javascript Fetch:使用Fetch响应和函数返回设置变量
我对JavaScript和react都是新手。 我有一个来自组件的回调,该组件从给定id的服务器获取客户名称。 fetch工作,console.log正确打印全名,但最后一个.then中的customer_名称未设置,函数返回空字符串。为什么呢Javascript Fetch:使用Fetch响应和函数返回设置变量,javascript,ajax,reactjs,fetch-api,Javascript,Ajax,Reactjs,Fetch Api,我对JavaScript和react都是新手。 我有一个来自组件的回调,该组件从给定id的服务器获取客户名称。 fetch工作,console.log正确打印全名,但最后一个.then中的customer_名称未设置,函数返回空字符串。为什么呢 // Gets the fullname of the customer from an id. tj_customer_name(id) { let customer_name = ''; fetch(`/customers/${id}.jso
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
let customer_name = '';
fetch(`/customers/${id}.json`, {
headers: API_HEADERS,
credentials: 'same-origin'
})
.then((response) => {
if(response.ok) {
return response.json();
} else {
throw new Error('Server response wasn\'t OK');
}
})
.then((json) => {
customer_name = json.first_name.concat(' ').concat(json.last_name);
console.log(customer_name);
});
return customer_name;
}
因为fetch是异步的,并且返回一个承诺,就其性质而言,只能异步观察(使用
.then
)
您可能只需返回在函数中创建的承诺链,并在最后一个中返回customer\u name
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
// return the entire promise chain
return fetch(`/customers/${id}.json`, {
headers: API_HEADERS,
credentials: 'same-origin'
})
.then((response) => {
if(response.ok) {
return response.json();
} else {
throw new Error('Server response wasn\'t OK');
}
})
.then((json) => {
const customer_name = json.first_name.concat(' ').concat(json.last_name);
return customer_name; // return the customer_name here
});
}
// later, use the function somewhere
this.tj_customer_name(21).then((customer_name) => {
// do something with the customer_name
});
PS:别忘了添加一个.catch
处理程序来处理潜在的网络问题(请参阅:)我认为您没有正确理解承诺。将在解析承诺之前调用return语句,从而返回空字符串
解决这个问题的一个方法是像这样回报整个承诺:
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
let customer_name = '';
return fetch(`/customers/${id}.json`, {
headers: API_HEADERS,
credentials: 'same-origin'
})
.then((response) => {
if(response.ok) {
return response.json();
} else {
throw new Error('Server response wasn\'t OK');
}
})
.then((json) => {
return json.first_name.concat(' ').concat(json.last_name);
});
}
或者您可以使用ES7方法,像这样使用async/await
async function tj_customer_name(id) {
const response = await fetch('some-url', {});
const json = await response.json();
return json.first_name.concat(' ').concat(json.last_name);
}
如您所见,第二种方法更加清晰易读
结果将与调用函数的代码中的结果相同
tj_customer_name(1).then(fullName => {
console.log(fullName);
});
或
您的“等待”示例返回一个承诺(请参阅)
async function something() {
const fullName = await tj_customer_name(1);
console.log(fullName);
}