Sequencing Asynchronous Operations
Returning a Promise within then()
Returning another Promise within a then() callback will cause the then() method to return the returned Promise.
Notice how returning a Promise within a then() callback creates a new promise with the returned promise's result:
let promise = Promise.resolve("hello");
let promise2 = promise.then(result => {
console.log(result) //logs "hello"
return Promise.resolve("12345") //causes then() to return a promise with a fulfillment value of "12345"
});
promise2.then(result => {
console.log(result); //logs "12345"
});
Sequencing Asynchronous Operations
Asynchronous Operations can be sequenced by returning Promises within then() callbacks.
Imagine that there are three asynchronous functions called getRandomNumber(), getNameFromNumber() and getAgeFromName() that return Promises.
The functions do the following:
- getRandomNumber() - asynchronously returns a random number
- getNameFromNumber() - takes in a number and asynchronously returns a name
- getAgeFromName() - takes in a name and asynchronously returns an age
If we wanted to first call getRandomNumber() to get an number, then call getNameFromNumber() to get a name from that number, and then lastly call getAgeFromName() on the returned name to get an age then we would have to sequence them correctly.
If they were normal synchronous functions then it would be simple and would look like this:
let number = getRandomNumber();
let name = getNameFromNumber(number);
let age = getAgeFromName(name);
However, since the functions are asynchronous, the number variable may be undefined by the time getNameFromNumber() is called and the name variable may be undefined by the time getAgeFromName() is called.
Thus, we need to do the following to sequence them correctly:
//getRandomNumber() returns a promise containing a random number
getRandomNumber().then(result => {
console.log(result) // 42
return getNameFromNumber(result); //returns a promise containing a string representing a name
}).then(result2 => {
console.log(result2) //"Bob"
return getAgeFromName(result2); //returns a promise containing a number representing an age
}).then(result3 => {
console.log(result3) //21
}.catch(error => {
console.log(error)
});
If any of the then() functions returns a rejected Promise then the catch() method will handle the rejected result.