Return 来自另一个文件的获取响应

Return the fetch response from another file

我正在尝试调用一个函数,该函数从单独文件中的 React 组件调用 API 的提取,但找不到正确的解决方案来获得正确的响应。

当我调试时,updateAccount 函数之前的 result returns 已经完成并且最终结果永远不会返回到我的 update 函数。

fetch、API returns 中正确响应是否成功或有验证错误,并且这些结果正确分配给 result.successresult.errorsresult 不会从函数返回,以便调用者可以使用这些值。

我的 React 组件内部:

import { updateAccount } from '../services/requests';
...
const update = (account: EditAccountModel) => {
  const result = updateAccount(account);
  if(result.errors.length > 0) {
    // will notify of errors
    console.log(result.errors); // is an empty array instead of validation errors
  } else {
    // will notify of success
    console.log(result.success); // is an empty string instead of success message
  }
}
...

我的请求文件

export const updateAccount = (account: EditAccountModel | undefined): EditAccountResponseModel => {
  const result = new EditAccountResponseModel();
  fetch(baseUrl, {
    method: 'PUT',
    body: JSON.stringify(account),
    headers 
  })
  .then(response => {
    if (!response.ok) {
      return Promise.reject(response);
    }
    result.success = `${account?.name} was updated successfully!`
  })
  .catch(error => {
    if (typeof error.json === "function") {
      error.json().then(jsonError => {
        result.errors.push(jsonError);
      }).catch(genericError => {
        result.errors.push(genericError);
      });
    }
  });
  return result;
}

result 重新分配发生在 then catch 内部,但它不会以您预期的方式产生影响。 return 正确结果的保证方法是通过 callback() 传递给您的 updateAccount() 如果您负担得起:


export const updateAccount = (
  account: EditAccountModel | undefined,
  callback: Function
): EditAccountResponseModel => {

  const result = new EditAccountResponseModel();

  fetch(baseUrl, {
    method: 'PUT',
    body: JSON.stringify(account),
    headers 
  })
  .then(response => {
    if (!response.ok) {
      return Promise.reject(response);
    }

    result.success = `${account?.name} was updated successfully!`
    callback(result);
  })
  .catch(error => {
    if (typeof error.json === "function") {
      error.json().then(jsonError => {
        result.errors.push(jsonError);
        callback(result);
      }).catch(genericError => {
        result.errors.push(genericError);
        callback(result);
      });
    }
    

  });
}

在你的 React 组件中:

const update = (account: EditAccountModel) => {
  const handleResult = (res) => {
    // your result callback code
    // ...
  };

  updateAccount(account, handleResult);
  // ...
}

保持当前结构的另一种方法是将当前的 updateAccount() 更改为 async 函数,然后 return await fetch().

您需要等待回复。我将详细介绍 Promise 在 JavaScript 中的工作原理。 我不会像您那样编写 updateAccount 代码,尤其是在您使用变量 result 并在 promise 流程中更新它的地方(您真的不需要那个)。您还使用了 React,因此您可以使用状态来存储和更新更新函数的结果。但让我们先解决您的问题:

export const updateAccount = async (account: EditAccountModel | undefined): EditAccountResponseModel => {
  const result = new EditAccountResponseModel();
  await fetch(baseUrl, {
    method: 'PUT',
    body: JSON.stringify(account),
    headers 
  })
  .then(response => {
    if (!response.ok) {
      return Promise.reject(response);
    }
    result.success = `${account?.name} was updated successfully!`
  })
  .catch(error => {
    if (typeof error.json === "function") {
      error.json().then(jsonError => {
        result.errors.push(jsonError);
      }).catch(genericError => {
        result.errors.push(genericError);
      });
    }
  });
  return result;
}

首先使您的函数 updateAccount async 然后 await 成为 promise 的结果。

现在函数 update:

同样的事情
const update = async (account: EditAccountModel) => {
  const result = await updateAccount(account);
  if(result.errors.length > 0) {
    // will notify of errors
  } else {
    // will notify of success
  }
}