首页 > 解决方案 > 对如何使用 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

有人可以引导我朝着正确的方向前进吗?

谢谢你。

标签: javascriptaxios

解决方案


如果您的后端准确地发送响应一个准确的数组,那么您应该

调用 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);

推荐阅读