Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
llamando variable fuera de la función

Estoy tratando de desarrollar una página web que obtenga los datos de otra aplicación web usando axios.get y quiero insertar estos datos en la base de datos de Postgres, el problema es que los datos están dentro de la promesa, no puedo acceder a ellos para insertarlos. a la base de datos, ¿cómo puedo hacer eso o cómo puedo acceder a los datos fuera del entonces quiero insertar var rn0 ty0 este es el 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);

este es 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
2 Respuestas
Responde la pregunta

0

Puedes encadenar promesas. Esto le dará suficiente flexibilidad para realizar una serie de acciones una tras otra, en su caso, cambie textContent y luego inserte algunos valores en la base de datos.

 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();
about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede hacer esto con la ayuda de Promise , aquí hay un ejemplo simple

 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();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda