简体   繁体   English

为什么我应该从我的Axios调用中返回“未定义”,什么时候应该返回对象?

[英]Why am I getting back “undefined” from my Axios call, when it should return me objects?

Problem Intro: 问题简介:

In my React app I'm making some API calls to Github to fetch some user data. 在我的React应用程序中,我对Github进行了一些API调用,以获取一些用户数据。 In another function I call these functions and wait for it with Axios's .all() method. 在另一个函数中,我调用这些函数,并使用Axios的.all()方法等待它。

I want to fetch the data and do something with it using .then() but the returned value is just an array with 2 times undefined 我想获取数据并使用.then()但返回的值只是一个未定义2倍的数组

What is the expected thing to happen: 预期会发生什么:

It should return me 2 player objects with profile infos in the profile key of the object and a score value in the score key of the object. 它应该返回给我2个玩家对象,并在对象的profile键中包含配置文件信息,并在对象的score键中包含得分值。

What is my app doing in a nutshell? 简而言之,我的应用程序在做什么?

It fetches the data from 2 usernames and they can "battle" each other. 它从2个用户名中获取数据,它们可以彼此“战斗”。 It just fetches the score and the followers and returns a sum. 它只是获取分数和关注者并返回总和。 At the end it (should) returns an array with 2 player objects already sorted with the winner in the first place ( exampleArray[0] ). 最后,它(应该)返回一个数组,其中包含2个玩家对象,这些对象已经排在首位( exampleArray[0] )。

General information's It's an react app using components. 一般信息是使用组件的React应用程序。 It's really about one very tiny component and the helper functions in another file. 它实际上是一个非常小的组件,而辅助函数则在另一个文件中。

Here is where I call my custom function (the one returning undefined): 这是我调用自定义函数的地方(一个返回未定义的函数):

componentDidMount() {
    const players = queryString.parse(this.props.location.search); //<== the usernames
    const playersArray = [players.playerOneName, players.playerTwoName];
    console.log(playersArray); // <== this logs the output as expected (an array with 2 usernames)

    battle(playersArray).then((data) => {   // <== the function it's all about
        console.log(data); // <== data is => [undefined, undefined];
    })
}

Next is the battle function from above that uses 2 other functions: 接下来是上面使用两个其他功能的战斗功能:

battle 战斗

export function battle(players) { // <== players aray with 2 usernames as string
return axios.all(players.map(getUserData)) // <== look 1 function below
    .then(sortPlayers) // <== two functions below
    .catch(handleError)
}

getUserData getUserData

let getUserData = (player) => {
axios.all([
    getProfile(player),
    getRepos(player)
]).then((data) => {
    return {
        profile: data[0],
        score: calculateScore(data[0], data[1])
    }
})
}

sortPlayers sortPlayers

let sortPlayers = (players) => {

return players.sort((a, b) => {
    return b.score - a.score;
})
}

Ok so they also use other functions but they are really not too complicated. 好的,因此它们还使用其他功能,但实际上并不太复杂。 Let me know when you need examples from the other little helpers too. 让我知道您什么时候也需要其他小帮手的帮助。

I tried it with placing the debugger in different spots in the code and console logged different things, but I can't come through (first time I'm really working with promises). 我尝试将调试器放置在代码中的不同位置,并在控制台中记录了不同的内容,但是我无法通过(我第一次真正使用Promise)。 Sitting now 2 hours in front of this tiny problem and I can't figure it out. 现在坐在这个小问题前面两个小时,我无法弄清楚。

I think the problem lies somewhere in battle function itself or getUserData 我认为问题出在战斗功能本身或getUserData

At the end a little screenshot, what the output of my console.log looks: http://prntscr.com/hz5abq 在最后的屏幕快照中,console.log的输出如下所示: http : //prntscr.com/hz5abq

Thanks in advance 提前致谢

getUserData needs to return the promise that it creates. getUserData需要返回它创建的承诺。 At the moment it's not returning anything, so an implicit undefined is returned, and thus players.map(getUserData) results in an array of [undefined, undefined] 此刻它什么都不返回,所以返回一个隐式的undefined,因此players.map(getUserData)导致[undefined, undefined]数组

Ie, do this: 即,执行以下操作:

let getUserData = (player) => {
    // VVV added return statement
    return axios.all([
        getProfile(player),
        getRepos(player)
    ]).then((data) => {
        return {
            profile: data[0],
            score: calculateScore(data[0], data[1])
        }
    })
}

You don't have anything being returned in getUserData . getUserData中没有返回任何内容。 Either add a return or remove the {} wrapping axios.all 添加return或删除{}包装的axios.all

let getUserData = (player) => {

    return axios.all([
        getProfile(player),
        getRepos(player)
    ]).then((data) => {
        return {
            profile: data[0],
            score: calculateScore(data[0], data[1])
        }
    })

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM