Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
Problema relacionado con las funciones asíncronas: la espera solo es válida en funciones asíncronas

En un archivo llamado getData.js, escribí el siguiente código

 module.exports = async function (page, id) { const options = { ... }; axios .request(options) .then((response) => { myData = JSON.stringify(response.data); return myData; }) .catch((error) => { console.error(error); }); };

Ahora, en mi archivo index.js principal, importé el módulo anterior y luego tengo este fragmento,

 const server = http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); let finalData = await getData(myPage, myID); res.end(finalData); });

Cuando ejecuto este nodo se bloquea y aparece este error

SyntaxError: await solo es válido en funciones asíncronas y los cuerpos de módulos de nivel superior

¿Cómo hago que mi código funcione? Pensé en usar async-await porque la respuesta. Los datos son muy grandes, pero claramente no entiendo completamente las funciones de async-await. En el módulo externo, si trato de devolver myData fuera del bloque .then y tampoco uso async-await, entonces obtengo datos finales indefinidos.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!