【问题标题】:JS not waiting for Promise to be fulfilled?JS 不等待 Promise 实现?
【发布时间】:2019-09-04 01:11:38
【问题描述】:

我正在尝试让我的应用程序在执行其他代码之前等待承诺返回,这取决于该数据。为此,我使用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

【问题讨论】:

标签: javascript node.js


【解决方案1】:

getGuild 函数必须等待 axios 承诺才能返回结果:

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

【讨论】:

    【解决方案2】:

    async 函数中不需要then,因为awaitthen 的语法糖。

    getGuild 没有从 Axios 返回一个 Promise,所以它不能被链接。

    应该是:

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

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

    【讨论】:

    • 成功了,谢谢!是的,我想我在尝试了太多东西后出于恐慌添加了捕获。当 StackOverflow 允许时,我会将其标记为已解决。
    • 很高兴它有帮助。
    • 我将这样的catch 称为“尝试/隐藏”,因为它就是这样做的 :) 好笔记
    猜你喜欢
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2020-12-07
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多