"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid jQuery Promises in Chained Functions While Maintaining Async Operations?

How to Avoid jQuery Promises in Chained Functions While Maintaining Async Operations?

Published on 2024-11-06
Browse:379

How to Avoid jQuery Promises in Chained Functions While Maintaining Async Operations?

Dodging jQuery Promises in Chained Functions

Despite recommendations to avoid jQuery promises, developers may face challenges when chaining async jQuery functions without using jQuery's promise handling mechanisms like .then() or .when(). To address this, consider the following approach:

jQuery promises are interoperable with JavaScript promises. This means you can mix and match them in your code without issues. All reputable libraries and native promises accept thenables from any implementation. As a result, in most cases, you can code as if all your promises are using the same implementation.

However, if you need to ensure that all .then() calls use your preferred implementation or implement non-standard features, it's essential to explicitly cast all promises on which you invoke methods directly. For example:

Promise.all([$.ajax(...), $.ajax(...)]) // Just works (native `then`)
$.ajax(...) // jQuery promise
Promise.resolve($.ajax(...)) // Explicit cast
.then(function(data) { // Native `then`
  return $.ajax(...); // Just works
})
.catch(...) // Use features of native promise

Remember, mixing jQuery and JavaScript promises is generally not a problem, but if you need explicit control over the implementation, use the explicit casting approach.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3