Using the result of one function in another

Asked

Viewed 38 times

0

var request = require('request');
request.get('https://r2d2-secret-pass.herokuapp.com/validate', function(err, resp, body){
  console.log(body);
});

function CheckPassword(password){
  var psw = /^[a-zA-Z0-9-]\w{1,6}$/;
  if (password.value.match(psw)){
    alert('Senha válida, redirecionando ..');
    document.location.assign(body);
    return false;
  }
  else{
    alert('Senha inválida. Tente novamente.');
    return true;
  }
}

I’m a beginner in Javascript and need to use the 'body' of the first function in the 'Document.location.assign' of the second, some tip on how to do ?

  • Try the following: before the request, put var body;.... and within the request put body = body;

  • @Sam returns me Undefined, even inside the 'body' I have a link to a youtube video

  • The request is asynchronous (AJAX). So the body variable does not yet exist in the function.

1 answer

0

You have two options:

  • a) or flames the request.get() inside CheckPassword
  • b)or save the url/body of request.get() and consume within CheckPassword

Option to)

var request = require('request');

function CheckPassword(password) {
  var psw = /^[a-zA-Z0-9-]\w{1,6}$/;
  if (password.value.match(psw)) {
    alert('Senha válida, redirecionando ..');

    request.get('https://r2d2-secret-pass.herokuapp.com/validate', function(err, resp, body) {
      if (!err) document.location.assign(body);
    });
    return false;
  } else {
    alert('Senha inválida. Tente novamente.');
    return true;
  }
}

Option b)

var request = require('request');
let url = '';
request.get('https://r2d2-secret-pass.herokuapp.com/validate', function(err, resp, body) {
  url = body;
});

function CheckPassword(password) {
  var psw = /^[a-zA-Z0-9-]\w{1,6}$/;
  if (password.value.match(psw)) {
    alert('Senha válida, redirecionando ..');
    document.location.assign(url);
    return false;
  } else {
    alert('Senha inválida. Tente novamente.');
    return true;
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.