Solution Review: Promises
In this lesson, we will discuss the solutions to the questions in the previous lesson.
We'll cover the following...
var promise = func1();promise.then(function(result1) {console.log(result1);return func2();}).then(function(result2) {console.log(result2);return result2%10;}).then(function(result3) {console.log(result3);});function func1() {return new Promise(function(resolve, reject) {setTimeout(function() {resolve("Hello");}, 1000);});}function func2() {return new Promise(function(resolve, reject) {setTimeout(function() {resolve(50);}, 1000);});}
For the code above, you had to answer the following question:
Explanation #
Run the code below to see the solution.
var promise = func1();promise.then(function(result1) {console.log(result1);return func2();}).then(function(result2) {console.log(result2);return result2%10;}).then(function(result3) {console.log(result3);});function func1() {return new Promise(function(resolve, reject) {setTimeout(function() {resolve("Hello");}, 1000);});}function func2() {return new Promise(function(resolve, reject) {setTimeout(function() {resolve(50);}, 1000);});}
As you can see, the correct option is A. Let’s discuss the code to understand the answer.
On line 1, there is a variable promise
that stores the promise returned from the function func1
.
var promise = func1();
Once, this promise is received, there is a series of .then
statements following it.
On line 5, the first .then
statement is called. It has a callback as its first parameter for when the promise is resolved. Inside this callback, there is a console.log
statement outputting the result received from the first promise, that is, the result from func1
.
.then(function(result1) {
console.log(result1);
//..
})
If you follow the code, you’ll find the definition of func1
on line 19. As you can see, it returns a promise with the result Hello
after a delay of 1000 milliseconds.
function func1() {
...