0

I'm trying to develop a web page that get the data from another web application using axios.get and I wanna insert this data into the Postgres database, the problem is data is inside the then promise, I can not access it to insert it to the database, how can I do that or how can I access the data outside the then I wanna insert var rn0 ty0 this is the 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'
const urlLAMP_1 = 'http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la'
function getDataLAMP_0(){
  axios.get(urlLAMP_0, {
    headers: {
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Origin':'*',
      "X-M2M-RI":"OM2M-webpage",
      'Authorization': `Basic ${token}`,
      'Accept': 'application/json',
      'mode': 'cors',
      'credentials': 'include',
      }
  })
  .then(function(response) {
        document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
        var rn0 = response.data['m2m:cin'].rn;
        document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
        var ty0 = response.data['m2m:cin'].ty;
        document.getElementById("ri0").textContent = response.data['m2m:cin'].ri;
        document.getElementById("pi0").textContent = response.data['m2m:cin'].pi;
        document.getElementById("ct0").textContent = response.data['m2m:cin'].ct;
        document.getElementById("lt0").textContent = response.data['m2m:cin'].lt;
        document.getElementById("st0").textContent = response.data['m2m:cin'].st;
        document.getElementById("cnf0").textContent = response.data['m2m:cin'].cnf;
        document.getElementById("cs0").textContent = response.data['m2m:cin'].cs;
        document.getElementById("con0").textContent = response.data['m2m:cin'].con;
  })
}
getDataLAMP_0();
InsertToDataBase.insertdatatolamp0(rn0,ty0);

this is the 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 };
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – ponury-kostek Oct 12 '21 at 17:32

2 Answers2

0

You can chain promises. This will give you enough flexibility to do a series of actions one after the other, in your case change textContent and then insert some values into the database.

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";
const urlLAMP_1 = "http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la";
function getDataLAMP_0() {
  axios
    .get(urlLAMP_0, {
      headers: {
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Origin": "*",
        "X-M2M-RI": "OM2M-webpage",
        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;
      document.getElementById("ri0").textContent = response.data["m2m:cin"].ri;
      document.getElementById("pi0").textContent = response.data["m2m:cin"].pi;
      document.getElementById("ct0").textContent = response.data["m2m:cin"].ct;
      document.getElementById("lt0").textContent = response.data["m2m:cin"].lt;
      document.getElementById("st0").textContent = response.data["m2m:cin"].st;
      document.getElementById("cnf0").textContent =
        response.data["m2m:cin"].cnf;
      document.getElementById("cs0").textContent = response.data["m2m:cin"].cs;
      document.getElementById("con0").textContent =
        response.data["m2m:cin"].con;

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

getDataLAMP_0();

Kuncheria
  • 1,182
  • 9
  • 16
  • thank you so much for your response, is still not working, but I think the problem is not from accessing the variable because this statement ```InsertToDataBase.insertdatatolamp0(0,1); ```run outside the then but it did not run inside of it not element insert into the database – Badr-Eddine El mostaine Oct 12 '21 at 17:54
  • @Badr-EddineElmostaine In that case, there is a chance that your api call is failing , and the then bocks not executing. Can you add a catch block after then. This might give us some clue. – Kuncheria Oct 13 '21 at 04:20
-1

You can do this with the help of Promise, here is a simple example

async function httpGetDataHandler() {
  const url = "https://jsonplaceholder.typicode.com/posts";
  const response = await fetch(url);
  const parsedJson = await response.json();
  const data = await parsedJson;

  return Promise.resolve(data);
}

const getDataLAMP_0 = () => {
  httpGetDataHandler()
    .then((data) => {
      // do your document.getElementById stuff in here

      // I'm just returning the first index value, you can do whatever you want like return rn0
      return data[0]
    })
    .then((data) => {
      console.log("insert to database: ", data);
    });
};

getDataLAMP_0();
zillBoy
  • 81
  • 2
  • 5
  • thank you so much for your response, is still not working, but I think the problem is not from accessing the variable because this statement `InsertToDataBase.insertdatatolamp0(0,1);` run outside the then but it did not run inside of it, no element inserts into the database – Badr-Eddine El mostaine Oct 12 '21 at 18:38