JavaScript Promises: chaining promises with non-promise objects. Why it works?

Viewed 1981

I'm learning about JavaScript Fetch API and I'm a bit confusing about Promises.

Consider this dummy example that prints "ok" in the console:

fetch(".")
.then(function(response) { // first then() call
    return response;
}).then(function(response) { // second then() call
    console.log("ok");
});

The page about the Response Object of the Fetch API says:

The fetch() call returns a promise, which resolves with the Response object associated with the resource fetch operation.

Well, since fetch() returns a Promise object I can understand that the first then() call works fine because a Promise object has this method. But the Response object returned in the chained call is not a Promise object. However the second call to then() method works!

Altering the dummy example prints undefined in the first console.log():

fetch(".")
.then(function(response) { // first then() call
    console.log(response.then)
    return response;
}).then(function(response) { // second then() call
    console.log("ok");
});

My questions is: Why this works? How the second call to then() works since the returned object does not have this method? Is it a kind of syntax sugar?

Thanks!

1 Answers
Related