【问题标题】:using axios with promise API将 axios 与 Promise API 一起使用
【发布时间】:2020-06-22 19:33:01
【问题描述】:

我在 React 应用程序中使用基于 Promise 的钩子从 API 获取异步数据。

我也在使用 Axios,一个基于 Promise 的 http 客户端来调用 API。

在另一个 Promise 中使用基于 Promise 的客户端是一种反模式吗?下面的代码似乎不起作用。

const getData = () => {
  return new Promise((resolve, reject) => {
    const url = "/getData";
    axios.get(url)
      .then(function(response) {
        resolve(response);
      })
      .catch(function(error) {
        reject(error);
      });
  });

const useAsync = (asyncFunction) => {
  const [value, setValue] = useState(null);

  const execute = useCallback(() => {
    setPending(true);
    setValue(null);
    setError(null);
    return asyncFunction()
      .then(response => setValue(response))
      .catch(error => setError(error))
      .finally(() => setPending(false));
  }, [asyncFunction]);

  useEffect(() => {
      execute();
  }, [execute]);

  return { execute, pending, value, error };
};
};

const RidesList = () => {
  const {
    pending,
    value,
    error,
  } = useAsync(getData);

【问题讨论】:

  • 您有什么理由不使用async await 吗?
  • 你遇到了什么错误?
  • 我需要查找异步等待。我认为每次调用都使用相同的钩子会使代码可读。我没有收到任何错误,我只看到承诺无限期等待。

标签: reactjs axios react-hooks es6-promise


【解决方案1】:

哦,伙计。我认为您对 Promise 的工作方式存在根本性的误解。 首先,axios 默认已经返回一个Promise。所以你getData的整个第一个函数可以简化为:

const getData = () => {
  const url = "/getData"
  return axios.get(url)
}

但是您的代码的内容似乎表明您想要一个可查询的 Promise - 因此您可以出于任何原因检查它的状态。以下是您将如何做到的示例,改编自 this snippet

function statusPromiseMaker(promise) {
  if (promise.isResolved) return promise
  let status = {
    pending: true,
    rejected: false,
    fulfilled: false
  }
  let result = promise.then(
      resolvedValue => {
        status.fulfilled = true
        return resolvedValue
      },
      rejectedError => {
        status.rejected = true
        throw rejectedError
      }
    )
    .finally(() => {
      status.pending = false
    })

  result.status = () => status
  return result
}

通过这种方式,您可以执行let thing = statusPromiseMaker(getData()) 之类的操作,如果您查找thing.status.pending,您将得到truefalse 等...

我实际上并没有运行上面的内容,我可能忘记了一两个括号,但希望这会有所帮助。

我必须承认 - 我从未见过这样的东西在野外使用过。我很想知道你实际上想通过这个来完成什么。

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 2020-03-25
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多