作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Cassandra
和 Node.Js
编写聊天应用程序。我在 Node.Js 中使用了 async/await 。但它不起作用。我的 app.js
片段:
const cassandra = require('./routes/cassandra');
....
//I have used socket based on my use-case.
socket.on('room-available', async (roomName) => {
let result = await cassandra.isRoomAvailable(roomName);
console.log(`result: ${result}`);
await socket.emit('room-available', result);
});
我的cassandra.js
片段:
var isRoomAvailable = async (roomName) => {
var query = 'select room_id from chat_rooms where room_name = ? ALLOW FILTERING';
//execute is cassandra's function.
return await client.execute(query,[roomName],(error, result) => {
if(error){
console.log(`error in inserting: ${error}`);
genericResponse['status'] = "error";
genericResponse['message'] = error;
genericResponse['responseObject'] = {};
console.log(`generic response error: ${JSON.stringify(genericResponse)}`);
return genericResponse;
}
else {
console.log(`roomID: ${JSON.stringify(result.rows)}`);
if(result.rows != null){
genericResponse['status'] = "sucess";
genericResponse['message'] = "True";
console.log("GenericResponse - available: " , genericResponse);
return genericResponse;
}else{
genericResponse['status'] = "sucess";
genericResponse['message'] = "False";
console.log("GenericResponse - not available: " , genericResponse);
return genericResponse;
}
}
});
}
问题:
result: undefined
roomID: [{"room_id":"0507a5e01097e04f117e8ac620957033b7d7f5ac"}, {"room_id":"0507a5e01097e04f117e8ac620957033b7d7f5ac"},{"room_id":"7eb482bc1cc8294399a90ae49ccf0f6d588a2aef"},{"room_id":"7eb482bc1cc8294399a90ae49ccf0f6d588a2aef"}]
GenericResponse - available: { status: 'sucess', message: 'True', responseObject: '' }
result
首先获得返回,这是未定义
。基本上,result
应该包含所有 roomID。请帮我解决这个问题。谢谢。
最佳答案
您正在使用基于回调的方法,该方法不会返回 promise 。
client.execute(query, [ 'someone' ], function(err, result) {});
尝试使用基于 promise 的版本,如下所示:
const isRoomAvailable = async roomName => {
const query = 'select room_id from chat_rooms where room_name = ? ALLOW FILTERING';
try {
const result = await client.execute(query, [ roomName ], { prepare: true });
} catch (err) {
// Do something here
}
};
有关详细信息,请参阅文档:https://docs.datastax.com/en/developer/nodejs-driver/4.3/features/promise-callback/
关于javascript - Async/Await 执行前仍返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59307338/
我是一名优秀的程序员,十分优秀!