我正在尝试让我的应用程序在执行其他代码之前等待 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
最佳答案
then
在 async
函数中不需要,因为 await
是 then
的语法糖。
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/