+ 1
Why does .then method return a promise object?
Can anyone give an easy explanation why .then method returns a promise object? I found in multiple places that "The then method returns a Promise which allows for method chaining." . But if I am not explicitly returning a promise in a .then handler then how is it returning an equivalent promise? [Please don't provide MDN link, I've already read it]. Thanks.
2 Respostas
+ 3
Take a look at this example,
function a(){
this.name="xyz",
this.then=(f)=>{
f()
return this
}
}
b=new a()
.then(()=>{console.log("bye")})
.then(()=>{console.log("hey")})
Consider b here as a new promise object. We call then method on it with a function passed to it like how things works(assuming) in promise. But if you take a look at then function it returns this (the object itself) that is hidden from us until you take a look at how original promise is implemented. By returning the object itself , we can chain them this way .
+ 1
Abhay
Thanks, making sense now. :D