Promise chaining is the idea of having multiple promises run in a sequence. For example, I want to take an address and convert that into coordinates, and take those coordinates and convert them into weather information; this is an example of needing to synchronize two things. Also, we can do that really easily using promise chaining.
In order to chain our promises, inside our success call we'll return a new promise. In our example, we can return a new promise by calling asyncAdd again. I'll call asyncAdd next to the res and console.log statements, passing in two arguments: the result, whatever the previous promise has returned, and some sort of new number; let's use 33:
asyncAdd(5, 7).then((res) => {
console.log('Result:', res);
return asyncAdd(res, 33);
Now we're returning a promise so we can add my chaining onto it by calling the then method again. The then method will to get called after we close the closing parenthesis for our previous then method. This will also take one or more arguments. We can pass in a success handler, which will be a function and an error handler, which will also be a function:
asyncAdd(5, 7).then((res) => {
console.log('Result:', res);
return asyncAdd(res, 33);
}, (errorMessage) => {
console.log(errorMessage);
}).then(() => {
}, () => {
})
Now that we have our then callbacks set up, we can actually fill them out. Once again we will get a result; this will be the result of 5 plus 7, which is 12, plus 33, which will be 45. Then, we can print console.log ('Should be 45'). Next, we'll print the actual value from results variable:
}).then((res) => {
console.log('Should be 45', res);
}, () => {
});
Now our error handler will also be the same. We'll have errorMessage and we'll print it to the screen using the console.log, printing errorMessage:
}).then((res) => {
console.log('Should be 45', res);
}, (errorMessage) => {
console.log(errorMessage);
});
Now what we have is some chaining. Our first then callback functions will fire based on the result of our first asyncAdd call. If it goes well, the first one will fire. If it goes poorly, the second function will fire. Our second then call will be based on the asyncAdd call, where we add 33. This will let us chain the two results together, and we should get 45 printing to the screen. We'll save this file, which will restart things inside nodemon. Eventually, we'll get our two results: 12 and our Should be 45. As shown in the following code image, we get just that, Result: 12 and Should be 45, printing to the screen:
