Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Promise Chaining

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

Oh, but now we can get even cooler! The .catch() handler above reads the responseText off of the jqXHR object and uses its error data:

... lines 1 - 2
(function(window, $, Routing) {
... lines 4 - 26
$.extend(window.RepLogApp.prototype, {
... lines 28 - 77
handleNewFormSubmit: function(e) {
... lines 79 - 86
this._saveRepLog(formData)
.then(function(data) {
... lines 89 - 90
}).catch(function(jqXHR) {
var errorData = JSON.parse(jqXHR.responseText);
self._mapErrorsToForm(errorData.errors);
});
},
... lines 96 - 156
});
... lines 158 - 175
})(window, jQuery, Routing);

If we want, we could simplify the code in the handler by doing that before we reject our Promise.

Controlling Resolved Values

Let me show you: copy the errorData line and move it down into the other .catch(). Now, when we call reject(), pass it this:

... lines 1 - 2
(function(window, $, Routing) {
... lines 4 - 26
$.extend(window.RepLogApp.prototype, {
... lines 28 - 95
_saveRepLog: function(data) {
return new Promise(function(resolve, reject) {
$.ajax({
... lines 99 - 108
}).catch(function(jqXHR) {
var errorData = JSON.parse(jqXHR.responseText);
reject(errorData);
});
});
},
... lines 116 - 157
});
... lines 159 - 176
})(window, jQuery, Routing);

As soon as we do that, any .catch() handlers will be passed the nice, clean errorData:

... lines 1 - 2
(function(window, $, Routing) {
... lines 4 - 26
$.extend(window.RepLogApp.prototype, {
... lines 28 - 77
handleNewFormSubmit: function(e) {
... lines 79 - 86
this._saveRepLog(formData)
.then(function(data) {
... lines 89 - 90
}).catch(function(errorData) {
self._mapErrorsToForm(errorData.errors);
});
},
... lines 95 - 157
});
... lines 159 - 176
})(window, jQuery, Routing);

We no longer need to worry about parsing the JSON.

Refresh! And submit the form. Yes! Now, if we ever need to call _saveRepLog() from somewhere else, attaching a .catch() handler will be easier: we're passed the most relevant error data.

Creating your own Promise objects is not that common, but it's super powerful, giving you the ability to perform multiple asynchronous actions and allow other functions to do something once they all finish.

Returning a Promise from a Handler

Now, there was an easier way to do this. Sometimes, inside a handler - like .then(), you'll want to make another asynchronous action:

... lines 1 - 2
(function(window, $, Routing) {
... lines 4 - 26
$.extend(window.RepLogApp.prototype, {
... lines 28 - 95
_saveRepLog: function(data) {
return new Promise(function(resolve, reject) {
$.ajax({
... lines 99 - 101
}).then(function(data, textStatus, jqXHR) {
$.ajax({
... lines 104 - 107
});
... lines 109 - 112
});
});
},
... lines 116 - 157
});
... lines 159 - 176
})(window, jQuery, Routing);

That's exactly what's happening in _saveRepLog(). In this case, you can actually return a Promise from your handler.

Here's a simpler version of how our code could have looked to solve this same problem. Well, simpler at least in terms of the number of lines.

The first $.ajax() returns a Promise, and we immediately attach a .then() listener to it. From inside of that .then(), we return another Promise. When you do this, any other chained handlers will not be called until that Promise, meaning, the second AJAX call, has completed.

Let me say it a different way. First, because we're chaining .then() onto the $.ajax(), the return value of _saveRepLog() is actually whatever the .then() function returns. And what is that? Both .then() and .catch() always return a Promise object.

And, up until now, the value used by the Promise returned by .then() or .catch() would be whatever value the function inside returned. But! If that function returns a Promise, then effectively, that Promise is what is ultimately returned by .then() or .catch().

Tip

Technically, .then() should return a new Promise that mimics that Promise returned by the function inside of it. But it's easier to imagine that it directly returns the Promise that was returned inside of it.

That's a long way of saying that other chained listeners, will wait until that internal Promise is resolved. In our example, it means that any .then() handlers attached to _saveRepLog() will wait until the inner AJAX call is finished. In fact, that's the whole point of Promises: to allow us to perform multiple asynchronous actions by chaining a few .then() calls, instead of doing the old, ugly, nested handler functions.

Phew! Ok! Let's move on to one last, real-world example of using a Promise: inside an external library.

Leave a comment!

0
Login or Register to join the conversation
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial uses an older version of Symfony... but since it's a JavaScript tutorial, the concepts are still ? valid!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.2.0",
        "symfony/symfony": "3.1.*", // v3.1.10
        "twig/twig": "2.10.*", // v2.10.0
        "doctrine/orm": "^2.5", // v2.7.1
        "doctrine/doctrine-bundle": "^1.6", // 1.10.3
        "doctrine/doctrine-cache-bundle": "^1.2", // 1.3.2
        "symfony/swiftmailer-bundle": "^2.3", // v2.4.0
        "symfony/monolog-bundle": "^2.8", // 2.12.0
        "symfony/polyfill-apcu": "^1.0", // v1.2.0
        "sensio/distribution-bundle": "^5.0", // v5.0.22
        "sensio/framework-extra-bundle": "^3.0.2", // v3.0.16
        "incenteev/composer-parameter-handler": "^2.0", // v2.1.2
        "friendsofsymfony/user-bundle": "~2.0@dev", // dev-master
        "doctrine/doctrine-fixtures-bundle": "~2.3", // v2.4.1
        "doctrine/doctrine-migrations-bundle": "^1.2", // v1.2.1
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "friendsofsymfony/jsrouting-bundle": "^1.6" // 1.6.0
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0", // v3.1.1
        "symfony/phpunit-bridge": "^3.0" // v3.1.6
    }
}
userVoice