Using Native Promises Instead of jQuery Deferred
Starting with OroCommerce 7.0, the frontend framework is transitioning away from jQuery Deferred in favor of native Promises. Native Promises provide
a standardized, modern, and more reliable way to handle asynchronous logic, and they integrate smoothly with newer features, such as async/await.
This document shows examples of replacing $.Deferred and $.when with equivalent Promise-based patterns.
Replacing initLayout().done() to initLayout().then()
Before (using .done() method) |
After (using .then() method) |
|---|---|
import BaseView from 'oroui/js/app/views/base/view';
const SomeView = BaseView.extend({
render: function() {
this.initLayout().done(() => {...});
}
});
export default SomeView;
|
import BaseView from 'oroui/js/app/views/base/view';
const SomeView = BaseView.extend({
render: function() {
this.initLayout().then(() => {...});
}
});
export default SomeView;
|
Replacing $.Deferred With Promise
Before (using $.Deferred) |
After (using native Promise) |
|---|---|
function loadData() {
var d = $.Deferred();
$.ajax({
url: '/api/data',
success: function (result) {
d.resolve(result);
},
error: function () {
d.reject('Request failed');
}
});
return d.promise();
}
loadData()
.done(function (result) {
console.log('Loaded:', result);
})
.fail(function (err) {
console.error(err);
});
|
function loadData() {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/api/data',
success: resolve,
error: function () {
reject('Request failed');
}
});
});
});
}
loadData()
.then(function (result) {
console.log('Loaded:', result);
})
.catch(function (err) {
console.error(err);
});
|
Replacing $.when With Promise.all
Before (using $.when) |
After (using Promise.all) |
|---|---|
$.when(loadUser(), loadSettings())
.done(function (user, settings) {
console.log(user, settings);
})
.fail(function () {
console.error('Failed');
});
|
Promise.all([loadUser(), loadSettings()])
.then(function ([user, settings]) {
console.log(user, settings);
})
.catch(function () {
console.error('Failed');
});
|
Using async/await (optional)
Native Promises can also be used with async/await, which can simplify
asynchronous code and make it easier to read.
async function init() {
try {
const result = await loadData();
console.log('Loaded:', result);
} catch (err) {
console.error(err);
}
}
init();
Summary of mappings
jQuery Deferred |
Native Promise |
Note |
|---|---|---|
|
|
Replace custom deferred wrappers. |
|
|
Success callback. |
|
|
Error callback. |
|
|
Runs whether success or failure. |
|
|
Returns array of results. |