Promise.all()在添加其他猫鼬模型.save()时失败

时间:2018-12-02 01:13:32

标签: mongodb mongoose mongodb-query mocha

运行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代码替换为include 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')代码已经运行。

1 个答案:

答案 0 :(得分:0)

如果数据库离您很远,或者它位于速度很慢的计算机上,则

您可能真的超过了2秒的超时时间。

您可以通过.timeout(ms)进行控制,如下所示:

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

将超时时间设置为5秒。

详细了解here

希望有帮助, 祝你好运!