javascript如何返回结果

时间:2020-02-20 16:10:46

标签: javascript jquery reactjs redux react-redux

我想在result函数中从response.on返回signIn

const signIn = async (password) => {
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  var response = client.authenticate(request, {}, (err, response) => {
      console.log("Request Sent 1111");
  });

  response.on('data', function(reply) {
      console.log("Data Received 2222");
      console.log('Data: 22222'+ reply.getAuthjwt());
      var result = reply.getAuthjwt()
      return result
  });

  return result;  
}

export {
    signIn
};

1 个答案:

答案 0 :(得分:-1)

您的结果变量超出范围。

var result;之外定义response.on,然后设置result = reply.getAuthjwt()

否则,我相信您应该能够return response.on,并且只需在函数内返回reply.getAuthjwt()

const signIn = async (password) => {
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  var response = client.authenticate(request, {}, (err, response) => {
      console.log("Request Sent 1111");
  });
  return response.on('data', function(reply) {
      console.log("Data Received 2222");
      console.log('Data: 22222'+ reply.getAuthjwt());
      return reply.getAuthjwt()
  });
}

export {
    signIn
};

const signIn = async (password) => {
  var result;
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  var response = client.authenticate(request, {}, (err, response) => {
      console.log("Request Sent 1111");
  });
  response.on('data', function(reply) {
      console.log("Data Received 2222");
      console.log('Data: 22222'+ reply.getAuthjwt());
      result = reply.getAuthjwt()
  });
  return result;
}

export {
    signIn
};

我也想知道您是否可以使用

const signIn = async (password) => {
  var result;
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  client.authenticate(request, {}, (err, response) => {
      response.on('data', function(reply) {
        console.log("Data Received 2222");
        console.log('Data: 22222'+ reply.getAuthjwt());
        result = reply.getAuthjwt()
     });
  });

  return result;  
}

export {
    signIn
};