首页 > 解决方案 > 反应:我在尝试添加 Axios 调用的服务中有一个 try/catch 块,但我不确定将它放在哪里

问题描述

我在 React 服务中有一个 try/catch 块,现在我需要添加实际的 Axios 调用并向外部 API 发出 GET 请求,以便取回实时数据,然后将该数据响应设置为现有变量,但我'不知道该怎么做。我在下面列出了我的服务,任何有关如何更好地完成此任务的反馈或见解将是一个巨大的帮助

客户服务.js

import { logError } from './logging'

export async function getCustomer(customer = {}) {
  try {
    const { customerId } = customer
    console.info('Customer ID:', customerId)

    // TODO: Make call to new API
    return new Promise(res => {
      setTimeout(() => res({}), 1000)
    })
  } catch (error) {
    logError(error)
    throw error
  }
}

标签: reactjsreact-reduxtry-catchaxios

解决方案


由于您的getCustomer()函数是async,您应该能够await调用 Axios :

import Axios from 'axios'
import { logError } from './logging'

export async function getCustomer(customer = {}) {
  try {
    const { customerId } = customer
    console.info('Customer ID:', customerId)

    const result = await Axios.get("http://example.com");

    return new Promise(res => {
      // I assume this is where you want to use the API result?
      setTimeout(() => res(result), 1000)
    })
  } catch (error) {
    logError(error)
    throw error
  }
}

推荐阅读