Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using console.log as a promise callback [duplicate]

I found it bit strange that, resolving a promise like this

.then(console.log, console.log)

doesn't work, but this works

 .then(d => {
     console.log(d);
   }, err => {
     console.log(err);
   });

what am I missing

like image 561
bsr Avatar asked Sep 25 '22 05:09

bsr


1 Answers

The console.log() function needs the console object as the value of this, or else it won't/can't work. You achieve that with the second bit of code because you're calling console.log() as one normally would. In the first code, however, you're "stripping" the reference to the function away from the object itself, so when the promise mechanism makes the function call it has no way of knowing that it should arrange for this to be the console object.

You could also do

.then(console.log.bind(console), console.log.bind(console))

though that's pretty ugly :)

like image 63
Pointy Avatar answered Oct 22 '22 09:10

Pointy