2016-05-09 43 views
0

我正在嘗試將承諾值傳遞給下一個承諾,並寫下以下行來測試它。爲什麼簡單的Promise聲明在瀏覽器中不起作用

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

很簡單,如果我在終端上運行的節點(4.3.0),我得到了想要的結果

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

然而,這並不是我得到在瀏覽器中的結果。

Firefox不會出錯,但從不記錄「嘿」;

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

Chrome的蟲子更

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

不具有堆棧跟蹤。

我試着看看Babel是否會把這段代碼翻譯成別的東西,但它根本不會改變這個說法。

什麼給? 如果我在我的代碼中使用這些語句,會不會破壞?

+0

'Promise.resolve( '嗨'),那麼(X => console.log(x));' –

+1

請注意,您可以使用'catch'在Firefox中看到缺少的錯誤(但您必須在'catch'中正確使用'console.log'才能看到它!):'' Promise.resolve('hey')。then(console.log).catch(x => console.log(x));' – apsillers

回答

1

你不能僅僅通過console.log,你需要直接與要記錄的值(S)稱之爲:

Promise.resolve('hey').then(function(s) { console.log(s); }); 
+0

其功能是不是? ...爲什麼? – lonewarrior556

+1

@ lonewarrior556調用函數作爲方法('foo.bar()')將擁有對象作爲'this'值提供給函數。當你以不同的方式調用同一個方法時,它會以不同的'this'值運行。要看到這個,做'bar = function(){return this;}; FOO = {欄:巴}; console.log(foo.bar(),bar())'。 'then'方法不會將'log'作爲'console'的''log'成員來調用。 – apsillers

+0

ahhhh,應該用google搜索它,但我沒有意識到console.log是問題所在。 – lonewarrior556

相關問題