Home > Back-end >  Returning a promise from JQuery "on ready" function
Returning a promise from JQuery "on ready" function

Time:06-28

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.

CodePudding user response:

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.

  • Related