0

I'm trying to pass a promise value to the next promise and wrote the line below to test it out.

Promise.resolve('hey').then(console.log);

simple enough, if I run node(4.3.0) in terminal I get the desired outcome

> Promise.resolve('hey').then(console.log);
Promise { <pending> }
> hey

However this is not the result I'm getting in browsers.

Firefox doesn't error out, but never logs "hey";

Promise.resolve('hey').then(console.log);
Promise { <state>: "pending" }
>
Promise.resolve('hey').then(console.log);
Promise { <state>: "pending" }
>

Chrome bugs out even more

Promise.resolve('hey').then(console.log);
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
undefined:1 Uncaught (in promise) TypeError: Illegal invocation

With no stack trace.

I tried to see if Babel would translate this code to something else but It does not change this statement at all.

What gives? Will this break if I use these statements in my code too?

lonewarrior556
  • 3,917
  • 2
  • 26
  • 55
  • `Promise.resolve('hey').then(x => console.log(x));` –  May 09 '16 at 18:36
  • 1
    Note that you can see the missing error in Firefox by using `catch` (but you have to use `console.log` correctly in `catch` in order to see it!): `Promise.resolve('hey').then(console.log).catch(x=>console.log(x));` – apsillers May 09 '16 at 18:47

1 Answers1

1

You can't just pass console.log, you need to call it directly with the value(s) you want to log:

Promise.resolve('hey').then(function(s) { console.log(s); });
Amit
  • 45,440
  • 9
  • 78
  • 110
  • its a function is it not? ... why? – lonewarrior556 May 09 '16 at 19:53
  • 1
    @lonewarrior556 calling a function as a method (`foo.bar()`) supplies the owning object as a `this` value to the function. When you call the same method in a different way, it runs with a different `this` value. To see this, do `bar=function(){return this;}; foo={bar:bar}; console.log(foo.bar(), bar())`. The `then` method does not invoke `log` as a member of `console`, which `log` requires. – apsillers May 09 '16 at 20:51
  • ahhhh, should have googled it, but I didn't realize the console.log was the issue. – lonewarrior556 May 10 '16 at 13:34