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

175
Views
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 answers
Answer question

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 Report
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!