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

时间:2016-08-10 09:21:15

标签: javascript ajax reactjs fetch-api

我对JavaScript很新并做出反应。 我有一个组件的回调,该组件从给定id的服务器获取customer_name。 fetch工作正常,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;
}

2 个答案:

答案 0 :(得分:17)

我认为你没有正确理解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);
  });
}

或者你可以使用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);
}

答案 1 :(得分:7)

因为fetch是异步的并且返回一个promise,它本质上只能异步观察(使用#include <stdio.h> int main() { int k, i, space, rows; printf("Enter the number of rows: "); scanf("%d", &rows); printf("\n"); for (i = rows; i >= 1; i--, k = 0) { for (space = 1; space <= rows - i; space++) { printf(" "); } printf("smth"); while (k < 2 * i - 1) { printf("* "); k++; } printf("\n"); } return 0; } )。

您应该只返回在函数中创建的promise链,并在链的最后.then回调中返回customer_name

.then

PS:不要忘记添加// 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 }); 处理程序来处理潜在的网络问题(请参阅:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful