Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
call function inside another function javascript

why this InsertToDataBase.insertdatatolamp0(1,1); insert the element into the database but the first one InsertToDataBase.insertdatatolamp0(0,0); did not.

please any solution to make the run InsertToDataBase.insertdatatolamp0(0,0);

main.js

const axios = require('axios')
const InsertToDataBase = require("./InsertToDataBase");
const username = 'admin'
const password = 'admin'
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const urlLAMP_0 = 'http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la'
function getDataLAMP_0(){
  axios.get(urlLAMP_0, {
    headers: {
      'Authorization': `Basic ${token}`,
      'Accept': 'application/json',
      'mode': 'cors',
      'credentials': 'include',
      }
  })
  .then(function(response) {
        document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
        document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
  })
  .then((response) => {
    var rn0 = response.data["m2m:cin"].rn;
    var ty0 = response.data["m2m:cin"].ty;
    InsertToDataBase.insertdatatolamp0(0,0);
  });
}
InsertToDataBase.insertdatatolamp0(1,1);
getDataLAMP_0();

InsertToDataBase.js

const {Client} = require('pg')
const client = new Client({
    user:"postgres",
    password:"admin",
    host:"localhost",
    port:"5432",
    database:"postgres",
})
function insertdatatolamp0(rn0,ty0){
client.connect()
.then(()=>console.log("connected successfuly"))
.then(()=>client.query("insert into lamp0 values ($1,$2)",[rn0,ty0]))
.catch(e=> console.log(e))
.finally(()=> client.end())
}
module.exports = { insertdatatolamp0 };
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In a promise chain, each step expects the result to be returned by the previous step.

In your promise chain, this step:

.then(function(response) {
  document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
  document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
})

does not return anything, which means it returns undefined. Therefore, the next step in the chain gets that response:

.then((response) => { // response here is undefined
  var rn0 = response.data["m2m:cin"].rn;
  var ty0 = response.data["m2m:cin"].ty;
  InsertToDataBase.insertdatatolamp0(0,0);
});

To make it work as expected, change the previous step to:

.then(function(response) {
  document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
  document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
  return response;
})

Side note: although InsertToDataBase.insertdatatolamp0(0,0); is higher up in code, you should not refer to it as "the first one". Because it's wrapped in a Promise() it will actually get executed later, when the promise resolves. Whereas InsertToDataBase.insertdatatolamp0(1,1); will be the first one executed.

about 4 years ago · Juan Pablo Isaza Relatório

0

Do you see the result of your call

axios.get(urlLAMP_0, {
    headers: {
      'Authorization': `Basic ${token}`,
      'Accept': 'application/json',
      'mode': 'cors',
      'credentials': 'include',
      }
  })

in the Networks tab of your browser?

.then() chain works only if your initial promise succeeds. If your requests hangs while on waiting state or fails, the chain never conitnues.

Also, there is a problem further in your chain

.then(function(response) {
        document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
        document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
  })
  .then((response) => {
    var rn0 = response.data["m2m:cin"].rn;
    var ty0 = response.data["m2m:cin"].ty;
    InsertToDataBase.insertdatatolamp0(0,0);
  });

response in first function is the result of the axios.get() promise. But as your first .then() returns nothing (it should return either promise or some value) it is treated as your function returning undefined by default, so second .then(response => ...) will get undefined response.

You have two options.

  1. Return response as a result of your first .then() or
  2. Combine first and second .then() clauses in one function.

2 is cleaner and better, you should use several .then()'s if only you return Promise in each of then to move further or you need some condition, like:

return axios.get(something)
  .then(response => {
     if (response.a) return axios.get(somethingElse)
     else return response
  })
  .then(response => {
    // here we have either initial response or response from the next get
  })

That is not realted directly to your question, but it's a bug.

about 4 years ago · Juan Pablo Isaza Relatório

0

Right now, you are "chaining" the insertion of the data using a series of .then() statements.

However, you are not passing the response down through this chain of .then calls, which could be your issue.

When writing promises in Javascript, you should also try to handle your errors. That will give you more information about what could be going wrong, otherwise Javascript will throw an uncaught exception error and it'll be difficult to debug.

I've added a few lines of code to your main.js file, that will hopefully point you in the right direction.

const axios = require('axios')
const InsertToDataBase = require("./InsertToDataBase");
const username = 'admin'
const password = 'admin'
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const urlLAMP_0 = 'http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la'
function getDataLAMP_0(){
  axios.get(urlLAMP_0, {
    headers: {
      'Authorization': `Basic ${token}`,
      'Accept': 'application/json',
      'mode': 'cors',
      'credentials': 'include',
      }
  })
  .then(function(response) {
        document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
        document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
        return response; // You must return the response here....

  })
  .then((response) => { // In order to get access to it here...
    // If you try to access response.data (where response === undefined) you will get an error! That may be happening, but you weren't handling the error.
    var rn0 = response.data["m2m:cin"].rn;
    var ty0 = response.data["m2m:cin"].ty;
    return InsertToDataBase.insertdatatolamp0(0,0);  
  })
  .then(() => {
    console.log("SUCCESS");
  })
  .catch((err) => { // And handle your error case!
    console.error(err);
   });
}
getDataLAMP_0();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda