简体   繁体   English

JS不等待Promise得到满足?

[英]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. 为此,我使用then() ,但它没有按预期工作,因为在返回我的值之前,下一个代码仍在执行。

I am using Express to handle requests and Axios to make my own requests. 我正在使用Express处理请求和Axios来发出我自己的请求。

index.js: 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: 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. 我已经知道getGuild(id)正在返回一个工作响应。 It also logs Returning guild data when returning the data. 它还会在返回Returning guild data时记录Returning guild data数据。 Yet this is being returned after index.js returning the error, that the response is undefined. 然而,这是 index.js返回错误之后返回的,即响应未定义。 Even though it should actually wait for the Promise to be fulfilled and then working with response.data . 即使它实际上应该等待Promise完成然后使用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 . thenasync函数中不需要,因为awaitthen语法糖。

getGuild doesn't return a promise from Axios, so it cannot be chained. getGuild不会从Axios返回承诺,因此无法链接。

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. getGuild使用catch是一种不好的做法,因为它可以抑制错误并防止在调用函数中处理它。

The getGuild function must wait for the axios promise in order to return a result: getGuild函数必须等待axios promise才能返回结果:

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;
}

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

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