执行前返回值的javascript函数

dsf9zpds  于 2021-06-10  发布在  Cassandra
关注(0)|答案(1)|浏览(441)

我正在写聊天应用程序使用 Node.Js 以及 Cassandra . 调用函数后在后端 saveDataToCassandra 它在将数据保存到之前返回 Cassandra . 它是 Cassandra 发行或 Javascript 问题?我的 app.js 代码段是:

const cassandra = require('./routes/cassandra');
....
let result = cassandra.saveDataToCassandra(reqData);
console.log(`result: ${JSON.stringify(result)}`);

我的 cassandra.js 代码段是:

var saveDataToCassandra = (req) => {
    const roomId = req.roomId;
    const roomName = req.roomName;
    let participants = [];
    participants = req.participant;
    console.log("participant's list",participants);
    const formatted_date  = req.roomCreationTimestamp;

    var query = `insert into chat_app.chat_rooms(room_id,room_name,participant_type,participant,role,room_creation_date) values (?,?,?,?,?,?);`;
    participants.forEach((participant) => {
        var params = [roomId, roomName, participant.type, participant.username,participant.role, formatted_date];
        console.log(`params: ${params}`);
        client.execute(query,params,{prepare: true},(error, result) => {
            if(error){
                console.log(`error in inserting: ${error}`);
                genericResponse['status'] = "error";
                genericResponse['message'] = error;
                genericResponse['responseObject'] = {
                    roomId: roomId,
                    userName: participant.username
                };
                console.log(`generic response error: ${JSON.stringify(genericResponse)}`);
            }
            else {
                console.log(`insert result: ${JSON.stringify(result)}`);
                genericResponse['status'] = "success";
                genericResponse['message'] = "Successfully Inserted!";
                genericResponse['responseObject'] = {
                    roomId: roomId,
                    roomName: roomName,
                    participant: participant.username
                }
                console.log(`generic response success: ${JSON.stringify(genericResponse)}`);    
            }
        });
    });
    console.log(`generic response before returning: ${JSON.stringify(genericResponse)}`);
    return genericResponse;
}

问题:

participant's list [ { username: 'alice',
    role: 'teacher',
    type: 'Owner' },
  { username: 'bob',
    role: 'student',
    type: 'participant' } ]
params:
    791c6abfaa962ca60abb776d04d89a32937024f5, alice&bob, Owner,alice,teacher,2019-12-12 17:33:54
params: 
    791c6abfaa962ca60abb776d04d89a32937024f5, alice&bob,participant,bob,student,2019-12-12 17:33:54
generic response before returning: {"status":"","message":"","responseObject":""}
result: {"status":"","message":"","responseObject":""}
insert result: {"info":{"queriedHost":"127.0.0.1:9042","triedHosts":{"127.0.0.1:9042":null},"speculativeExecutions":0,"achievedConsistency":10,"isSchemaInAgreement":true},"columns":null,"pageState":null}
generic response success: {"status":"success","message":"Successfully Inserted!","responseObject":{"roomId":"791c6abfaa962ca60abb776d04d89a32937024f5","roomName":"alice&bob","participant":"alice"}}
insert result: {"info":{"queriedHost":"127.0.0.1:9042","triedHosts":{"127.0.0.1:9042":null},"speculativeExecutions":0,"achievedConsistency":10,"isSchemaInAgreement":true},"columns":null,"pageState":null}
generic response success: {"status":"success","message":"Successfully Inserted!","responseObject":{"roomId":"791c6abfaa962ca60abb776d04d89a32937024f5","roomName":"alice&bob","participant":"bob"}}

现在的问题是 saveDataToCassandra 他回来了 genericResponse 数据首先存储在 Cassandra . 我想在将数据保存到后返回响应 Cassandra . 请帮我解决这个问题。提前感谢:)

uhry853o

uhry853o1#

我猜你构建代码的方式不是写。您正在foreach循环中调用回调样式的函数,当您调用方法时,您没有等待。如果像这样提取execute方法

function execute(participant, query) {
  return new Promise((resolve, reject) => {
    client.execute(query,params,{prepare: true}, (error, result) => {
    if(error){
        console.log(`error in inserting: ${error}`);
        genericResponse['status'] = "error";
        genericResponse['message'] = error;
        genericResponse['responseObject'] = {
            roomId: roomId,
            userName: participant.username
        };
        console.log(`generic response error: ${JSON.stringify(genericResponse)}`);
        reject(genericResponse);
    }
    else {
        console.log(`insert result: ${JSON.stringify(result)}`);
        genericResponse['status'] = "success";
        genericResponse['message'] = "Successfully Inserted!";
        genericResponse['responseObject'] = {
            roomId: roomId,
            roomName: roomName,
            participant: participant.username
        }
        console.log(`generic response success: ${JSON.stringify(genericResponse)}`); 
        resolve(genericResponse);   
    }
  });
});

像这样更改保存方法-基本上使用promise all而不是foreach

var saveDataToCassandra = (req) => {
  const roomId = req.roomId;
  const roomName = req.roomName;
  let participants = [];
  participants = req.participant;
  console.log("participant's list",participants);
  const formatted_date  = req.roomCreationTimestamp;

  var query = `insert into chat_app.chat_rooms(room_id,room_name,participant_type,participant,role,room_creation_date) values (?,?,?,?,?,?);`;
  return Promise.all(participants.map(participant => {
      var params = [roomId, roomName, participant.type, participant.username,participant.role, formatted_date];
      console.log(`params: ${params}`);
      return execute(participant, query);
  }));
};

然后在需要结果时使用

const cassandra = require('./routes/cassandra');

cassandra.saveDataToCassandra(reqData)
  .then(result => console.log(result));

您也可以使用async/await,但这个示例使用的是承诺。希望这有帮助。

相关问题