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

k3r*_*n31 9 javascript ajax reactjs fetch-api

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

kud*_*ajz 23

我认为你没有正确理解Promises.在解析Promise之前将调用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);
  });
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,第二种方法更清晰,更易读.

调用函数的代码中的结果是相同的

tj_customer_name(1).then(fullName => {
    console.log(fullName);
});
Run Code Online (Sandbox Code Playgroud)

要么

async function something() {
    const fullName = await tj_customer_name(1);
    console.log(fullName);
}
Run Code Online (Sandbox Code Playgroud)

  • 您的“await”示例返回一个承诺(请参阅/sf/ask/4242626811/#60608981) (2认同)

nil*_*ils 7

因为fetch是异步的,并且返回一个promise,但从本质上说,只能异步(使用.then)观察到它。

您可能应该只返回在函数中创建的promise链,然后返回该链customer_name的最后一个.then回调:

// 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
});
Run Code Online (Sandbox Code Playgroud)

PS:不要忘记添加一个.catch处理程序来处理潜在的网络问题(请参阅:https : //developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful