sequelize.js - 创建行但 promise 不解决

标签 sequelize.js chai chai-as-promised

使用 seqalizerjs,解决一个 promise :

return new Promise(function(resolve, reject){
            return models.merchants.create({
                name: ctx.name,
            });
        }).then(function(result){
            resolve({
                id: result.id
            });
        }).catch(function(err){
            reject(err);
        });

以 chai 作为 promise 进行测试
return user.save(data).should.eventually.equal('123123');

但我总是得到这个:
 Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure
 it resolves.

最佳答案

我认为问题出在这一行:

return new Promise(function(resolve, reject){
        return models.merchants.create({
            name: ctx.name,
        });
        // .....
Promise函数应该有 resolve() ,像这样:
return new Promise(function(resolve, reject){
        resolve(models.merchants.create({
            name: ctx.name,
        }));

基于 this reference :

The resolve and reject functions are bound to the promise and calling them fulfills or rejects the promise, respectively.



仍然基于引用,有Promise流程图:
enter image description here
then()catch()之后 Promise()不处理 resolve()也不是 reject() ,它们只处理从 resolve() 传递的值或 reject() .

所以,我认为你的代码应该是这样的:
return new Promise(function(resolve, reject){
    resolve(models.merchants.create({
        name: ctx.name,
    }));
}).then(function(merchants){
    console.log(merchants) // the created `merchants` from the `resolve()` of the promise would be passed here.
    return merchants;
});

更新

您的代码应如下所示:
return new Promise(function(resolve, reject){
    models.merchants.create({ // assuming `models.merchants.create()` is an async method
        name: ctx.name,
    }).then(function(result){
        resolve({
            id: result.id
        });
    }).catch(function(err){
        reject(err);
});

关于sequelize.js - 创建行但 promise 不解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46597811/

相关文章:

javascript - 为什么这个 chai-as-promised AssertionError 打印到控制台而不是我的 Mocha 测试运行程序?

node.js - Sequelize 如何不在每次服务器启动时重新定义模型

mysql - Sequelize 如何比较日期的年份和月份

node.js - 如何在 mocha 的 mocha.opts 文件中添加 chaijs 的断言?

node.js - chai.assert.isRejected 消息验证器不起作用

javascript - 在 Chai.js 中使用 promises 的深度相等(测试)

node.js - sequelize index 选项运行两次并导致测试失败

node.js - 检索时更改表的名称

javascript - Chai 深等于不工作