gpt4 book ai didi

javascript - Async/Await 执行前仍返回数据

转载 作者:行者123 更新时间:2023-12-01 00:22:22 25 4
gpt4 key购买 nike

我正在使用 CassandraNode.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com