Let's look at jQuery first as an introduction to learning promises.
What does this code return? What is the value of result
?
var result = $('body');
Hint: It won't be the <body/>
body HTML element.
result
is a jQuery collection object. Internally it holds a reference to the body tag. But the actual result
object is a collection.
What does this return?
var result = $('body').css('background', 'red');
Again, it returns a jQuery collection.
And this?
var result = $('body').css('background', 'red').animate({height: "20px"});
Same thing. A jQuery collection.
Now, what does this promise based code return?
var result = new Promise();
It's probably clear this returns a promise. But what about this code?
var result = new Promise().resolve().then(() => {
return 'Hello';
});
What is the value of result
now? Hint: It's not the string 'Hello'
.
It's a promise!
What does this return?
var result = new Promise().resolve().then(() => {
return new Promise().resolve();
}).then(() => {
return 'Hello';
}).catch(() => {
console.log('Something went wrong');
});
It returns a promise! Promises let us access values in functions that are called at later times. Until the function is executed, you won't have access to whatever the promise "returns," or "resolves" with. Once you enter a promise chain, you always have to use .then(fn)
to handle the next step in the program flow.
Javascript is asynchronous. All top level code is executed in order without pausing. The promise resolves at a later time, long after your console.log
has finished executing. To get values back, you need to stay in promise chain land:
g().then( result => console.log(result) );