So I'm trying to grasp Promises and as of now I think I'm understanding everything I've read so far except for one example listed on MDN Web Docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) which I modified.
Original goes like this:
Promise.resolve('foo')
// 1. Receive "foo" concatenate "bar" to it and resolve that to the next then
.then(function(string) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
string += 'bar';
resolve(string);
}, 1);
});
})
// 2. receive "foobar", register a callback function to work on that string
// and print it to the console, but not before return the unworked on
// string to the next then
.then(function(string) {
setTimeout(function() {
string += 'baz';
console.log(string);
}, 1)
return string;
})
// 3. print helpful messages about how the code in this section will be run
// before string is actually processed by the mocked asynchronous code in the
// prior then block.
.then(function(string) {
console.log("Last Then: oops... didn't bother to instantiate and return " +
"a promise in the prior then so the sequence may be a bit " +
"surprising");
// Note that `string` will not have the 'baz' bit of it at this point. This
// is because we mocked that to happen asynchronously with a setTimeout function
console.log(string);
});
Which indeed was surprising, but eventually understood (well, at least I think I understood) why it happened that way.
Now, I changed the second .then
to:
.then(function(string) {
setTimeout(function() {
string += 'baz';
console.log(string);
return string;
}, 1)
And I'm getting that the last .then
is being executed before the second .then
returns a value. According to the MDN, "When a value is simply returned from within a then handler, it will effectively return Promise.resolve()." Shouldn't the next .then
wait for it to Resolve or Reject (which implies waiting for the Timeout callback to execute) in order to execute?
Let me say sorry in advance if I'm missing something obvious or my question is dumb. And thank you!