我是JavaScript新手并做出反应.我有一个组件的回调,该组件从给定id的服务器获取customer_name.提取工作正常,console.log正确打印全名,但最后一个.then中的customer_name未设置,并且函数返回一个空字符串.这是为什么?
// 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;
}
Run Code Online (Sandbox Code Playgroud)