窗口:与承诺
问题描述:
我试图让我的头围绕错误的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>
难道我做错了什么? 谢谢
答
您正在使用的代码将在浏览器中,因为那是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
}
您有评论'检查浏览器是否支持Promises',但你不运行这个脚本在浏览器中,这是'窗口'将被定义的地方。 – Gavin
有没有窗口,在命令行... – baao
卫生署!当然!对错误抱歉... – antobbo