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

146
Views
Detectar si la función fue llamada con "entonces"

Estoy haciendo mi propia función ajax como jQuery y esto es lo que tengo hasta ahora

 const ajax = function(options){ const defaults = { type: 'GET', url: window.location, data: {}, success: function(){}, error: function(){} }, opts = {...defaults, ...options}; const xhr = new XMLHttpRequest(); xhr.addEventListener("load", function(){ opts.success.call(this, xhr.response, xhr); }); xhr.addEventListener("error", function(){ opts.error.call(this, xhr); }); xhr.open(opts.type, opts.url); xhr.send(); }

y puedo llamarlo así

 ajax({ success: (data) => { console.log(data); } });

Funciona. Pero quiero agregarle una promesa opcional . Así que quiero poder llamar a esta función exactamente así pero también como

 ajax().then(data => { console.log(data); }).catch(error => { console.log(error); });

Soy nuevo en las promesas, así que no estoy seguro de cómo modificar la función para que pueda detectar si resolver/rechazar o llamar a las devoluciones de llamada. ¿También estoy haciendo algo que se considera una mala práctica?

 const ajax = function(options){ const defaults = { type: 'GET', url: window.location, data: {}, success: function(){}, error: function(){} }, opts = {...defaults, ...options}; return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.addEventListener("load", function(){ resolve(xhr.response); }); xhr.addEventListener("error", function(){ reject(xhr); }); xhr.open(opts.type, opts.url); xhr.send(); }); }
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!