So, I understand that .then()
returns a new Promise
that can be chained to another .then()
.
The following example, though, has me confused. This tutorial is saying that the final .then()
in the example cannot be extended unless it explicitly returns a new Promise
.
// Make a request for user.json
fetch('/article/promise-chaining/user.json')
// Load it as json
.then(response => response.json())
// Make a request to GitHub
.then(user => fetch(`https://api.github.com/users/${user.name}`))
// Load the response as json
.then(response => response.json())
// Show the avatar image (githubUser.avatar_url) for 3 seconds
.then(githubUser => {
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => img.remove(), 3000); // (*)
});
They are saying that the final .then()
cannot be extended, and that it has to be written to explicitly return a new Promise
, like this:
fetch('/article/promise-chaining/user.json')
.then(response => response.json())
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(response => response.json())
.then(githubUser => new Promise(function(resolve, reject) { // *
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => {
img.remove();
resolve(githubUser); // (**)
}, 3000);
}))
// triggers after 3 seconds
.then(githubUser => alert(`Showed ${githubUser.name}`));
Could someone please explain to me why all the other instances of .then()
we could chain without having to explicitly return a new Promise
, but why with that last one we couldn’t?
Thank you.