javascript - 对如何使用 axios 正确处理 javascript 承诺有些困惑
问题描述
所以我有两个简单的函数,第一个函数进行 api 调用并检索 100 个类别 ID 并将它们存储在一个数组中。我使用 lodash 随机选择其中的 6 个类别 ID。第二个函数假设使用这 6 个唯一的类别 ID,并在查询字符串中使用它们,以便在第二个函数中进行接下来的 6 个 api 调用。
async function getCategoryIds() {
const res = await axios.get('http://jservice.io//api/categories?count=100');
for (let cat of res.data) {
categories.push(cat.id)
}
var sampleCategories = _.sampleSize(categories, 6);
console.log(sampleCategories);
return sampleCategories;
}
getCategoryIds()
.then(getCategory)
async function getCategory(sampleCategories) {
const res1 = await axios.get(`http://jservice.io/api/category?id=${sampleCategories[0]}`);
const res2 = await axios.get(`http://jservice.io/api/category?id=${sampleCategories[1]}`);
const res3 = await axios.get(`http://jservice.io/api/category?id=${sampleCategories[2]}`);
const res4 = await axios.get(`http://jservice.io/api/category?id=${sampleCategories[3]}`);
const res5 = await axios.get(`http://jservice.io/api/category?id=${sampleCategories[4]}`);
const res6 = await axios.get(`http://jservice.io/api/category?id=${sampleCategories[5]}`);
}
getCategory();
但是,无论我如何返工,我仍然无法消除此错误:
Uncaught (in promise) TypeError: Cannot read property '0' of undefined
有人可以引导我朝着正确的方向前进吗?
谢谢你。
解决方案
如果您的后端准确地发送响应一个准确的数组,那么您应该
调用 getCategory 函数时不要忘记提供参数
然后编辑您的 getCategory 函数
async function getCategory(sampleCategories) {
let arr = []
const res1 = await axios.get('any url you want')
//repeat 6 times
arr = [res1, res2, ...otherElems]
return arr
}
使用 'then' 语法
getCategoryIds()
.then(response => getCategory(response))
使用异步等待语法
const firstResponseArr = await getCategoryIds();
const secondResponseArr = await getCategory(firstResponseArr);
推荐阅读
- javascript - Angular js代码在使用错误后终止
- rxjs - ngx-select-dropdown 如何包含 debounceTime?
- spring-boot - 当spring boot应用程序在linux中部署为服务时,如何动态传递或指定application.yml?
- c++ - 在引用初始化中使用已删除的复制构造函数进行复制初始化
- jwt - 如何配置并告诉 Auth0 使用 Authorities (JWT) 返还身份验证令牌
- c# - 将另一个对象的值分配给这个 c#
- spring - 无法使用 Spring Boot 生成 DDL 创建脚本
- ios - 无法将记录添加到 SQLite 数据库
- django - 在 Django 中创建用户后如何返回 JWT 令牌?
- reactjs - MUI ThemeProvider 未在已编译组件中注入主题