小编k3r*_*n31的帖子

Fetch:使用fetch响应设置变量并从函数返回

我是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)

javascript ajax reactjs fetch-api

9
推荐指数
2
解决办法
3万
查看次数

标签 统计

ajax ×1

fetch-api ×1

javascript ×1

reactjs ×1