Javascript函数在执行前返回值

时间:2019-12-12 12:54:31

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

我正在使用Node.JsCassandra编写聊天应用程序。在调用函数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后,我想返回响应。请帮我解决这个问题。在此先感谢:)

1 个答案:

答案 0 :(得分:0)

我想您编写代码的方式不是写的。您正在foreach循环中调用回调样式函数,并且在调用方法时,您没有在等待。如果您这样提取执行方法

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,但是本示例使用的是Promise。希望这会有所帮助。