I've been implementing some features in javascript using promises, but am confused about one thing, difference b/w these two
Promise.resolve()
.then(doSomething())
and
.then(() => doSomething())
I've been implementing some features in javascript using promises, but am confused about one thing, difference b/w these two
Promise.resolve()
.then(doSomething())
and
.then(() => doSomething())
then
expects a function. In the first case, you're passing to then
the result of calling doSomething()
, and in the second case you're actually passing a function that calls doSomething()
.
Those would be equivalent (assuming you don't need arguments or this
):
Promise.resolve().then(doSomething)
Promise.resolve().then(() => doSomething())
.then(doSomething())
immediately invokes doSomething
before the then
callback is called.
.then(() => doSomething())
creates a new function which becomes the then
callback.
To expand on @Lucas answer, which is correct, then
in a Promise is formulated like this (from MDN):
Promise.then(onFulfilled[, onRejected]);
Promise.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
So your first argument is a function for fulfillment, and your second function an argument for a rejection, both arguments being functions, to which values are passed based on that which occurred.
So, as @Lucas said,
Promise.resolve().then(() => doSomething())
actually calls your function, where as just passing in doSomething()
calls the function and returns a value or undefined if there is no return, which will do nothing unless that function returns a function (which would probably be an unreasonable way to go about a thenable).