javascript - JS 不等待 Promise 完成吗?

标签 javascript node.js

我正在尝试让我的应用程序在执行其他代码之前等待 promise 返回,这取决于该数据。为此,我使用了 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。然而,这是在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 返回 Promise,因此无法链接。

应该是:

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

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

关于javascript - JS 不等待 Promise 完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55665704/

相关文章:

javascript - 动态返回配置值(node.js)

node.js - Node REPL "on exit"事件

javascript - Socket.io:接收事件触发多次

javascript - 在范围内定位变量?

ios - react 原生 ios 构建 : Can't find node

node.js - 您可以使用 node-libcurl 设置源 header 吗?

node.js - Node : How to test middleware making external call

javascript - highstock 图表点击获取最近点

javascript - 如何简化重复的函数

javascript - 我的 requirejs 设置有什么问题?