About Promises and Complex Code Flow
Use JavaScript promises for time-consuming asynchronous tasks.
Here is an example of a default promise call:
function get_results(params) {
return new Promise(function(resolve, reject) {
/*
Here go logical operations or tasks that call
resolve(data); on success
or
reject('Error message.'); on errors
*/
});
}
And here is an example of less nested alternative:
function get_results(params) {
let deferred = null;
let promise = new Promise(function(resolve, reject) {
deferred = {resolve: resolve, reject: reject};
});
/*
Here go logical operations or tasks that call
deferred.resolve(data); on success
or
deferred.reject('Error message.'); on errors
*/
return promise;
}
Then you can use the promise as follows:
get_results({query: 'DjangoTricks', page: 2}).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
The then()
handling function is triggered, when the promise is resolved. The catch()
handling function is triggered, when the promise is rejected.
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django App for You
Django GDPR Cookie Consent app
For Django websites that use cookies.
Django App for You