简体   繁体   中英

JS not waiting for Promise to be fulfilled?

I'm trying for my application to wait for the promise to return before executing other code, which is dependant on that data. For this I am using then() , but it is not working as expected, as the next code is still being executed, before my values are being returned.

I am using Express to handle requests and Axios to make my own requests.

index.js:

app.get('/api/guild/:serverId', async (req,res) => {
    bot.getGuild(req.params.serverId).then((response) => { // It should here wait for the promise before executing res.send(...)...
        res.send(response.data);
    }).catch((error) => {
        console.log(error) // Error: Returns that response is undefined
    });
});

bot.js:

module.exports.getGuild = async function (id){
    axios.get(BASE_URL + `guilds/${id}`, {
        headers: { 
            'Authorization' : 'Bot ' + token // Send authorization header
        }
    }).then(function (response){ // Wait for response
        console.log("Returning guild data")
        return response; // Sending the response and also logging
    }).catch(function (error){
        console.log("Returning undefined.")
        return undefined; // This is not being used in my problem
    });
}

I already know that getGuild(id) is returning a working response. It also logs Returning guild data when returning the data. Yet this is being returned after index.js returning the error, that the response is undefined. Even though it should actually wait for the Promise to be fulfilled and then working with response.data .

Log:

TypeError: Cannot read property 'data' of undefined
    at bot.getGuild.then (...\website\src\server\index.js:47:27)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Returning guild data

then is not needed in async functions because await is syntactic sugar for then .

getGuild doesn't return a promise from Axios, so it cannot be chained.

It should be:

module.exports.getGuild = function (id){
    return axios.get(BASE_URL + `guilds/${id}`, {
    ...

The use of catch in getGuild is a bad practice because it suppresses an error and prevents it from being handled in caller function.

The getGuild function must wait for the axios promise in order to return a result:

try {

    let res = await axios.get(BASE_URL + `guilds/${id}`, {
        headers: {
            'Authorization': 'Bot ' + token // Send authorization header
        }
    })

    console.log("Returning guild data")
    return res

} catch (exp) {
    console.log("Returning undefined.")
    return undefined;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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