首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >React:我在试图添加Axios调用的服务中有一个try/catch块,但我不确定该把它放在哪里

React:我在试图添加Axios调用的服务中有一个try/catch块,但我不确定该把它放在哪里
EN

Stack Overflow用户
提问于 2019-05-23 04:52:33
回答 1查看 20关注 0票数 0

我在React服务中有一个try/catch块,现在我需要添加实际的Axios调用,并向外部API发出GET请求,以便获取实时数据,然后将该数据响应设置为现有变量,但我不确定如何执行此操作。我在下面列出了我的服务,任何关于如何更好地实现这一点的反馈或见解都将是一个巨大的帮助

customerService.js

代码语言:javascript
复制
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
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-23 05:18:27

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

代码语言:javascript
复制
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
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56264858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档