繁体   English   中英

JS不等待Promise得到满足?

[英]JS not waiting for Promise to be fulfilled?

我正在尝试让我的应用程序在执行其他代码之前等待承诺返回,这依赖于该数据。 为此,我使用then() ,但它没有按预期工作,因为在返回我的值之前,下一个代码仍在执行。

我正在使用Express处理请求和Axios来发出我自己的请求。

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

我已经知道getGuild(id)正在返回一个工作响应。 它还会在返回Returning guild data时记录Returning guild data数据。 然而,这是 index.js返回错误之后返回的,即响应未定义。 即使它实际上应该等待Promise完成然后使用response.data

日志:

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

thenasync函数中不需要,因为awaitthen语法糖。

getGuild不会从Axios返回承诺,因此无法链接。

它应该是:

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

getGuild使用catch是一种不好的做法,因为它可以抑制错误并防止在调用函数中处理它。

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