异步/等待仍在执行前返回数据

时间:2019-12-12 14:58:30

标签: javascript node.js asynchronous cassandra async-await

我正在使用CassandraNode.Js编写聊天应用程序。我在async/await中使用过Node.Js。但这是行不通的。 我的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首先获得回报,即undefined。基本上,result应该包含所有roomID。请帮我解决这个问题。谢谢。

2 个答案:

答案 0 :(得分:1)

您正在使用基于回调的方法,该方法不会返回promise。

client.execute(query, [ 'someone' ], function(err, result) {});

尝试使用基于承诺的版本,如下所示:

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/

答案 1 :(得分:0)

如果您希望代码异步,请尝试将其设置为以下格式

const isRoomAvailable = async roomName => {
  try {
    let query = "select room_id from chat_rooms where room_name = ? ALLOW FILTERING";
    let result = await client.execute(query, [roomName]).promise();
    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;
    }
  } catch (e) {
    console.log(`error in inserting: ${error}`);
    genericResponse["status"] = "error";
    genericResponse["message"] = error;
    genericResponse["responseObject"] = {};
    console.log(`generic response error: ${JSON.stringify(genericResponse)}`);
    return genericResponse;
  }
};