• Hallo zusammen! Ich habe schon wieder mal ein Problem mit Javascript in Verbindung mit async und await.

    Ich weiß nicht warum, aber meine Variable wartet nich auf den return meiner async-Funktion.

    Hier mal der Code:

    const axios = require('axios');
    
    (async () => {
        
        const topicData = await getTopicData(apiUrl);
    
        console.log(topicData);
    
    
    })();
    
    
    async function getTopicData(apiUrl){
    
        axios.get(apiUrl, {
            headers: {
                'Authorization': `Bearer ${baerertoken}`
            }
        })
        .then((res) => {
            
            return res.data;
            
        })
        .catch((error) => {
            console.error(error);
        })
    
    }
    
    

    Meine Variable topicData ist immer undefined. Ich weiß nicht ob ich’s immer noch nicht verstanden habe aber jedenfalls verhält es sich anders als erwartet… Warum? 🙉


  • Du vermisst ein return vor axios


  • Yes dein return returned aus der axios function. Du musst also davor bei axios.get noch ein Return machen damit er aus deiner getTopicData returned.
    @cooper


  • Danke 🙂 funzt! 👌

    const axios = require('axios');
     
    (async () => {
        
        const topicData = await getTopicData(apiUrl);
     
        console.log(topicData);
     
     
    })();
     
     
    async function getTopicData(apiUrl){
     
        return axios.get(apiUrl, {
            headers: {
                'Authorization': `Bearer ${baerertoken}`
            }
        })
        .then((res) => {
            
            return res.data;
            
        })
        .catch((error) => {
            console.error(error);
        })
     
    }
    

Ähnliche Themen