【发布时间】: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