【问题标题】:Node - ReferenceError: Promise is not defined节点 - ReferenceError:未定义承诺
【发布时间】:2015-12-06 02:31:14
【问题描述】:

我从 Node.js 开始。抱歉,这可能是一个愚蠢的问题。

试图理解为什么下面的代码会抛出错误:ReferenceError: Promise is not defined

allAccountFixtures: ['account-customer-joe', 'account-partner-sam', 'account-partner-jane', 'account-admin-jill'],
allProductFixtures: ['product-123', 'product-234', 'product-345', 'product-456'],
...
loadBasicFixtures: (Api) => {
    return Promise.all([
      Support.importRecords(Api.accountsAPI, Support.allAccountFixtures),
      Support.importRecords(Api.productsAPI, Support.allProductFixtures)
   ]);
},

我的 API 在其他地方被定义为:

this.accountsAPI = app.service('/api/accounts');
this.productsAPI = app.service('/api/products');

导入函数为:

importRecords: (feathersService, fixtureNames) => {
    // Wrap in an array if there's only one.
    if (!(fixtureNames instanceof Array)) { fixtureNames = [fixtureNames]; }

    // Create a separate promise for each JSON fixture to load the JSON from a
    // file and send it to feathers.create(). Don't execute yet.
    var promises = fixtureNames.map(fixtureName => {
      var filePath = `test/fixtures/json/${fixtureName}.json`;
      // console.log(`-> Loading JSON fixture: ${filePath}`);

      return fs.readFileAsync(filePath, 'utf8')
        .then((jsonString) => {
        return JSON.parse(jsonString);
      }).then((json) => {
        return feathersService.create(json);
      });
    });

    // Wrap all fixture loading promises inside a single outer promise that will
    // fire when all of the child promises are complete.
    return Promise.all(promises);
},

不知道所提供的信息是否足以说明正在发生的事情。我查找了“承诺”的概念,差不多就是这样。也许你可以指出正确的方向。文档中提到了解决和拒绝。

【问题讨论】:

  • 你运行的是什么版本的 node.js?任何更新的 4.x 版本都将内置 Promise
  • 你是对的。我安装了 nvm 并将所有内容更改为 4.2.1

标签: javascript node.js webpack feathersjs


【解决方案1】:

因为它解决了你的问题,所以我会把我的评论变成答案。

一些旧版本的 node.js 没有内置 Promise,要使用 Promise 需要加载一个添加 Promise 支持的第三方库。

如果您升级到任何 4.x 版本的 node.js 或更高版本,您将在 node.js 中内置 Promise。

【讨论】:

    【解决方案2】:

    你需要 import 和 require Promise

    npm install promise --save
    

    然后

    var Promise = require('promise');
    

    【讨论】:

      猜你喜欢
      • 2017-04-19
      • 2014-06-05
      • 2020-02-29
      • 2018-10-11
      • 2021-11-08
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多