How to change the value of a variable within a javascript function

Asked

Viewed 1,319 times

0

I have a problem and I don’t know how to solve it, I’m new in javascript and I can’t change a value of an external variable within an internal function of . then:

var DadosCadastrados = function(){
    var dados = 1;
    User.findAll().then(cads => {
        dados = 2;
    }).catch(erro =>{
        dados = 3
    })
    console.log(dados)
    return dados
}

data is still printed as 1 and not as 2. how do I change its value? (Obs: the function then is being called and I put a console.log(data) inside then and it returns 2, but it returns 1 again)

  • The variable given = 1 is in the Globa scope and the others are inside an Arow Function, the variables inside a function are not visible outside the function. Therefore, the.log console will return the variable from outside the function.

2 answers

1

Hello, I believe you want to return find result, the problem is that find is an asynchronous method so then call can be executed after function returns, could give 2 suggestions:

  1. Check the possibility of using async await
  2. use a file to return the function result

Ex.:

var DadosCadastrados = function(){
    return new Promise(function(resolve, reject) {
      User.findAll().then(cads => {
          resolve(2);
      }).catch(erro =>{
          resolve(3)
      })
    })
}

DadosCadastrados().then(v => {
  console.log(v);
})

1


Notice that your function has asynchronous parts and so you can’t have one return of a synchronous value.

The return you expect from this function has to be consumed with a .then( asynchronously. Consequently if you want to have a return of the then internal and the catch internal you have to return something inside that then and catch and also return to Promise who is this User.findAll().

I made an example where I change the idea of User.findAll() by a Promise that solves or fails to show the two lines of logic in action:

const DadosCadastrados = function(resolution) {
  return Promise[resolution]().then(cads => {
    return 'passou';
  }).catch(erro => {
    return 'falhou';
  });
}

DadosCadastrados('resolve').then(res => console.log(res)); // passou
DadosCadastrados('reject').then(res => console.log(res)); // falhou

Browser other questions tagged

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