-->

Why would I get a “Promise is not defined.” error

2019-03-25 02:35发布

问题:

Im using autoprefixer with postcss and after moving to a new linux server something must be wrong but I cant figure out what this one could be. I'm getting the error:

/home/ec2-user/Enviziion/Muveoo/Server/node_modules/postcss/lib/lazy-result.js:157
        this.processing = new Promise(function (resolve, reject) {
                              ^
ReferenceError: Promise is not defined

Which is triggered by:

var autoprefixer = require('autoprefixer');
var postCSS = require('postcss');

function prefix(css, res, type, fullPath) {
    postCSS([autoprefixer]).process(css).then(function(result) {
        var css = result.css;
        var length = css.length;
        res.writeHead(200, {
            'Content-Length' : length,
            'Content-Type' : type
        });
        res.write(css);
        res.end();
    });
}

I researched this problem but all of the occurrences of the issue seem to be for extremely early versions of node.js, for example:

  • Native Support for Promises in Node.js

  • https://github.com/postcss/postcss-nested/issues/30

And the solution always seems to be "Update Node".

But mine seems to be up to date:

[ec2-user@ip-172-31-22-79 Server]$ node -v
v5.7.0

What might my issue be here?

回答1:

I cant answer why this is happening, but after reinstalling all npm packages, I still had the same error, so I used this very old solution to "monkeypatch" Promises into node:

npm install es6-promise

and then add the code:

var Promise = require('es6-promise').Promise;

And that "solved" the problem.

Edit (a year later): people are still up-voting this answer so I just want to point out to anyone encountering this, the question has gotten a ton of views and seems to be a common issue considering how weird it is - a deduction I later made was that the only reasonable explanation is that one of my libraries (perhaps many libraries do this same thing) built before promises were introduce, had them implemented manually and caused a conflict when Node was updated to support promises officially.

You might be running a legacy version of a maintained library for whatever reason (sometimes necessary to avoid maintenance of your older servers) or be running a current version of an old library that's no longer maintained. Either way, this solution seems to work.



回答2:

Upgrading node to latest version(v4.5.0) did resolved this issue.