获取:使用获取响应设置变量并从函数返回[重复]

2024-05-03

我对 JavaScript 和 React 还很陌生。 我有一个来自组件的回调,该组件从给定 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;
}

我认为你没有正确理解 Promise。 return 语句将在 Promise 解析之前被调用,从而返回空字符串。

解决这个问题的一种方法是像这样返回整个承诺:

// 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);
});

or

async function something() {
    const fullName = await tj_customer_name(1);
    console.log(fullName);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取:使用获取响应设置变量并从函数返回[重复] 的相关文章

随机推荐