node.js - 类型错误 : Cannot call method 'then' of undefined

标签 node.js promise sails.js bluebird sails-orientdb

我在 Sailsjs 的 Controller 内执行以下代码。底层适配器是 sails-orientdb。我收到以下错误消息

类型错误:无法调用未定义的“then”方法

为什么会出现这个错误?

        User.query("select id from User where username='" + req.param("userid") + "'").then(function(userData){
        console.log(userData);
        return userData;
    }).fail(function (err) {
        console.log("Handled");
    });

最佳答案

扩展 @jaumard 所说的内容。

背景

通常建议使用standard waterline query methodsfind()update()create()destroy()等这些方法支持回调和 promise ,这些方法将以相同的方式针对任何水线适配器(OrientDB、MySQL、MongoDB 等)工作。

有时您可能想要做一些更复杂的事情,这是标准水线方法不支持的,为此 sails-orientdb 使用 query() 扩展了水线定义,其中 other methods .

sails-orientdb .query()

sails-orientdb 查询使用回调,因此您可以像这样使用它:

  // Assume a model named "Friend"
  Friend.query("SELECT FROM friendTable WHERE name='friend query'", function(err, retrievedUsers){
    console.log(retrievedUsers);
  });

更新:自 v0.10.53 以来,还支持以下内容:

Friend.query("SELECT FROM friendTable WHERE name='friend query'")
.then(function(retrievedUsers){
  console.log(retrievedUsers);
});

如果你真的想使用 Promise 机制,你有两个选择:

promisify query()

通过使用bluebird promise 就是 promise 。示例:

var queryPromise = Promise.promisify(User.query);
queryPromise('select...').then(function(){/*...*/})

使用getDB()

另一个选择是使用 sails-orientdb 自定义方法 getDB 。此方法返回 Oriento db 实例,可用于 promise 查询。示例:

User.getDB().query('select from OUser where name=:name', {
  params: {
    name: 'Radu'
  },
  limit: 1
}).then(function (results){
  console.log(results);
});

关于node.js - 类型错误 : Cannot call method 'then' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29323819/

相关文章:

javascript - 从 Typescript 转译时 NodeJS 存在导入问题

javascript - Promise then 和 catch 条款不起作用

javascript - 理解 Node.js 中的 Promise

javascript - 在 SailsJS 0.9.7 中手动包含 Assets

javascript - 将 sails 路线路径添加到默认 URL

unit-testing - 使用 Mocha 或 Jasmine 对 Node.js REST 服务进行单元测试

linux - 在 Linux 上运行 node.js 时如何解决 "Server terminated early with status 127"?

node.js - supertest 测试删除方法返回 404 但 restful 客户端工作

javascript - 有条件的返回 promise : throwing vs returning null

node.js - Sails js -模型结果集变量范围