最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AsyncAwait with JQuery document READY - Stack Overflow

programmeradmin5浏览0评论

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;
}

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;
}
Share Improve this question edited Nov 16, 2021 at 5:54 Phil 165k25 gold badges261 silver badges267 bronze badges asked Nov 16, 2021 at 5:32 Venda 97Venda 97 2851 gold badge2 silver badges10 bronze badges 8
  • 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 Commented Nov 16, 2021 at 5: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 Commented Nov 16, 2021 at 5:41
  • Works fine here ~ jsfiddle/d40cjmfL – Phil Commented Nov 16, 2021 at 5:43
  • 1 @Phil I checked my JQuery, its version is 3.2.1. Can it be because of that? – Venda 97 Commented Nov 16, 2021 at 5:51
  • 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 Commented Nov 16, 2021 at 6:02
 |  Show 3 more ments

1 Answer 1

Reset to default 15

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 remended to use instead. JQuery docs

发布评论

评论列表(0)

  1. 暂无评论