reactjs - 反应:我在尝试添加 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
}
}
解决方案
由于您的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
}
}
推荐阅读
- docker - 在容器内使用 webgl 和 Nvidia GPU 运行无头 Chrome
- google-bigquery - 如何使用 WHERE NOT 过滤掉我的条件
- sql - 在 SQL 中进行多次更新的最高效方式
- c# - 它没有感应到我的 input.getaxis 是否有原因
- colors - 更改任务栏图标的颜色
- node.js - 尽管表单输入已成功传输到后端,为什么 JSON.parse(event.body) 返回 null?(包括代码和日志)
- asp.net-web-api - .Net Framework API 控制器无法识别路由属性
- javascript - 创建分层/缩进下拉列表
- php - 我正在尝试使用此表单来捕获用户详细信息并使用底部的 PHP 脚本将它们加载到 MySQL 表中,但它不起作用
- python - Ansible 是否公开其自动发现的 Python 解释器?