7

It works with document.addEventListener("DOMContentLoaded", async () => {}) but I am curious of making it work with JQuery.

And also, I want with Async/Await, not promises because later I will need the variable outside of promise callback.

let products = [];

$(document).ready(async function() {      // Does not work with ASYNC
    await getProducts();                  // IF i dont use async await, products = empty
    products.forEach(product => console.log(product))
})

const getProducts = () => {
   // Ajax call to server
   // products = ajaxResult;              // asign variable to result
   // returns Promise;
}
Phil
  • 157,677
  • 23
  • 242
  • 245
Venda 97
  • 225
  • 2
  • 10
  • What do you mean by _"does not work"_? Also... _"later I will need the variable outside of promise callback"_ async / await does not solve this problem for you – Phil Nov 16 '21 at 05:38
  • 1. if I use ASYNC next to function, it does not run at all. 2. I mean I will need the products variable several time later on in the program. So I want it to be assigned first and then use it easily without using getProducts().then() – Venda 97 Nov 16 '21 at 05:41
  • Works fine here ~ https://jsfiddle.net/d40cjmfL/ – Phil Nov 16 '21 at 05:43
  • 1
    @Phil I checked my JQuery, its version is 3.2.1. Can it be because of that? – Venda 97 Nov 16 '21 at 05:51
  • Seems you've found the issue, it fails to work on JSFIddle with that version too. Works with 3.3.1 onwards. Problem reproduced here ~ https://jsfiddle.net/d40cjmfL/2/ – Phil Nov 16 '21 at 05:53
  • It's 2021, [you might not need jQuery](https://youmightnotneedjquery.com/). There shouldn't be any harm upgrading though – Phil Nov 16 '21 at 05:58
  • 1
    @Phil You are right but the whole project is done on JQuery already. It will take time to reproduce everything into Vanilla JS. Yet, thank you for your time, Phil. – Venda 97 Nov 16 '21 at 06:02

1 Answers1

11

The problem was due to JQuery version 3.2.1 and maybe in some lower versions as well. $(document).ready(async function() {}) is fine to be used in later versions however.

$(document).ready( handler ) is deprecated as @Phil mentioned below.

$(handler) is recommended to use instead. JQuery docs

IbraHim M. Nada
  • 693
  • 6
  • 26
Venda 97
  • 225
  • 2
  • 10
  • 2
    FYI the `$(document).ready( handler )` syntax is deprecated. The advice in the [jQuery docs](https://api.jquery.com/ready/#ready-handler) is to use `$( handler )` – Phil Nov 16 '21 at 06:09
  • 1
    @Phil Yes, thanks, I forgot to mention it. – Venda 97 Nov 16 '21 at 06:19