【问题标题】:Promise.all() fail when additional mongoose model.save() is added in当添加额外的 mongoose model.save() 时,Promise.all() 失败
【发布时间】:2019-05-03 17:27:46
【问题描述】:

运行 4 次猫鼬模型保存时,我的 Promise.all 中出现 Mocha 错误,但仅运行 3 次猫鼬模型保存时没问题。这是 describe () => {} 下的示例代码。

// Blog and Tag are mongoose models.
beforeEach((done) => {
    myBlog = new Blog({ title: '1st Post' });
    myBlog2 = new Blog({ title: '2nd Post' });
    tag1 = new Tag({ tag: 'Tag 1' });
    tag2 = new Tag({ tag: 'Tag 2' });

    myBlog.tag.push(tag1, tag2);        
    myBlog2.tag.push(tag1);
    tag1.blog.push(myBlog, myBlog2);
    tag2.blog.push(myBlog);

    Promise.all([myBlog.save(), tag1.save(), tag2.save()])
        .then(() => done());
});

it('find myBlog', (done) => {       
    Blog.findOne({ title: '1st Post'})
        .then((blog) => {
            assert(blog.title === '1st Post');
            done();
        });
});

以上代码运行良好,但是当我将初始 Promise.all 代码替换为包含 myBlog2.save() 时,出现错误。

Promise.all([myBlog.save(), myBlog2.save(), tag1.save(), tag2.save()])
        .then(() => done());

"before each" hook for "find myBlog":
 Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

为什么在 Promise.all() 中添加额外的 model.save() 会导致错误?

我检查了 mongodb,集合确实保存成功。但是,我根本不相信 it('find myBlog') 代码会运行。

【问题讨论】:

    标签: mongodb mongoose mongodb-query mocha.js


    【解决方案1】:

    如果数据库离你很远,或者它在一个非常慢的机器上,

    你可能真的超过了 2 秒超时。

    你可以像这样通过 .timeout(ms) 来控制它:

    it('mytest', done => {}).timeout(5000)beforeEach().timeout()

    将超时设置为 5 秒。

    阅读更多关于它的信息here

    希望对你有帮助, 祝你好运!

    【讨论】:

    • 数据库在我的电脑中是本地的。我还发现它可以在 mocha 框架之外工作。
    • 请与我分享?你做了什么不同的事情?
    猜你喜欢
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    相关资源
    最近更新 更多