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

187
Vistas
Returning a promise from JQuery "on ready" function

According to the JQuery docs, the "recommended" syntax for executing code when the DOM objects become safe to manipulate (a.k.a. "on ready") is this syntax:

$(function() {
  // Handler for .ready() called.
});

The JQuery documentation makes no mention of what JQuery does with the return value, if any, provided by the function. Which brings me to my question: I want to await a promise in my function. Is there any reason why I can't decorate the function with the required async keyword, like this:

$(async function() {
  await someFuncThatReturnsAPromise();
});

According to the excellent JavaScript.info tutorial on the subject, the await keyword causes the function to return a resolved promise object. If JQuery doesn't care about the function result, then the fact that the function returns a promise object should (hopefully) have no effect on the underlying "call the page ready handlers" JQuery behavior.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It doesn't really do anything with the value returned, even if it's a Promise - and, for that reason, is a problem, because if the Promise rejects, you'll get an unhandled rejection:

$(async function() {
  await Promise.reject();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

(Specifically, what happens with the callback is - it's added as a .then handler to the internal readyList, and although there's a .catch chained onto it, it'll just re-throw the value returned.)

var readyList = jQuery.Deferred();

jQuery.fn.ready = function (fn) {

    readyList
        .then(fn)

        // Wrap jQuery.readyException in a function so that the lookup
        // happens at the time of error handling instead of callback
        // registration.
        .catch(function (error) {
            jQuery.readyException(error);
        });

    return this;
};

If the async function never rejects, then

$(async function() {
  await someFuncThatReturnsAPromise();
});

is just fine.

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