2016-11-17 84 views
-3

我試圖讓我的頭圍繞錯誤的JavaScript承諾,因爲我從來沒有使用過。 現在,我已經看了一些教程,並在this one我決定嘗試的代碼,但是當我運行此:在命令node promise.js Windows控制檯窗口:與承諾

if (window.Promise) { // Check if the browser supports Promises 
    var promise = new Promise(function(resolve, reject) { 
    //asynchronous code goes here 
    }); 
} 

我可以看到這個錯誤:

C:\Users\antobbo\Desktop\pdfSearch\promise.js:1 
(function (exports, require, module, __filename, __dirname) { if (window.Promise) { // Check if the browser supports Promises 
                   ^

ReferenceError: window is not defined 
    at Object.<anonymous> (C:\Users\antobbo\Desktop\pdfSearch\promise.js:1:67) 
    at Module._compile (module.js:570:32) 
    at Object.Module._extensions..js (module.js:579:10) 
    at Module.load (module.js:487:32) 
    at tryModuleLoad (module.js:446:12) 
    at Function.Module._load (module.js:438:3) 
    at Module.runMain (module.js:604:10) 
    at run (bootstrap_node.js:394:7) 
    at startup (bootstrap_node.js:149:9) 
    at bootstrap_node.js:509:3 

C:\Users\antobbo\Desktop\pdfSearch> 

難道我做錯了什麼? 謝謝

+4

您有評論'檢查瀏覽器是否支持Promises',但你不運行這個腳本在瀏覽器中,這是'窗口'將被定義的地方。 – Gavin

+0

有沒有窗口,在命令行... – baao

+0

衛生署!當然!對錯誤抱歉... – antobbo

回答

0

您正在使用的代碼將在瀏覽器中,因爲那是window將被定義。

如果是這樣的Node.js,那麼你可能已經知道你正在運行的是什麼版本的Node.js的,因爲你控制自己的環境,讓你可以提前知道的時間,無論您是節點的版本已經內置在承諾與否。

如果您正在編寫其他人的代碼來運行,並且您可能不知道其運行的node.js版本,那麼您可能只需要一個Promise polyfill來負責爲您檢查。有幾個在NPM或者你可以使用一個更全功能的圖書館像Bluebird(這是我用什麼,甚至比原生的承諾更先進的)。

如果你真的想測試的Promise在node.js的存在,那麼你這樣做:

// Check if the node.js Promises 
if (typeof Promise === "function") { 
    // yes native promises are supported 
}