About Promises and Complex Code Flow

Use JavaScript promises for time-consuming asynchronous tasks.

Here is an example of a default promise call:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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:

1
2
3
4
5
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.

Tips and Tricks Programming JavaScript