Is there any difference in efficiency? Will the behavior be any different if a setTimeout is used instead of console.log()
A then call will return a rejected promise if the function throws an error or returns a rejected Promise. In all other cases, a resolving Promise is returned.
then() method to access the value of a promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value of the promise as a parameter.
In the above program, a Promise object is created that takes two functions: resolve() and reject() . resolve() is used if the process is successful and reject() is used when an error occurs in the promise. The promise is resolved if the value of count is true.
You can basically do these three things
.then(console.log())
This calls the console.log immediately, without waiting until the promise is resolved, so it is not probably something that you would want to do.
.then(console.log)
This executes the console.log only after the promise has successfully resolved (requires one function call) and implicitly pass the result of the promise to to the console.log function.
.then(() => console.log())
Same as before, requires 2 function calls but you can easily pass some other arguments to it.
To pass additional argument to the console.log in the second case, you need to use Function.prototype.bind
method.
const promise = new Promise((resolve, reject) => {
resolve('');
});
promise.then(console.log.bind(console, 'new arg'));
And to see all the three cases mentioned above in action
const promise1 = new Promise((resolve, reject) => {
resolve('promise 1');
});
promise1.then(console.log());
const promise2 = new Promise((resolve, reject) => {
resolve('promise 2');
});
promise2.then(console.log);
const promise3 = new Promise((resolve, reject) => {
resolve('promise 3');
});
promise3.then(v => console.log(v));
In the first case, console.log didn't receive and arguments. In the second case, the console.log received value from promise implicitly and in the third case it received the same value but explicitly.
In this scenario, the only difference in performance between the second and third case is that the third case performed one more function call (which is something that we don't really have to worry about).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With