Bluebird——在处理程序中创建了一个承诺,但没有从中返回

Ant*_*rov 3 javascript mongoose node.js promise bluebird

首先,我知道我必须return保证避免出现此警告。我还尝试按照文档中的null建议返回。考虑这段代码,我在 Mongoose 的预保存挂钩中使用它,但我在其他地方遇到过这个警告:

var Story = mongoose.model('Story', StorySchema);

StorySchema.pre('save', function(next) {
    var story = this;

    // Fetch all stories before save to automatically assign
    // some variable, avoiding conflict with other stories
    return Story.find().then(function(stories) {

        // Some code, then set story.somevar value
        story.somevar = somevar;
        return null;
    }).then(next).catch(next); // <-- this line throws warning
});
Run Code Online (Sandbox Code Playgroud)

我也尝试过(最初)这种方式:

        story.somevar = somevar;
        return next(); // <-- this line throws warning
    }).catch(next);
Run Code Online (Sandbox Code Playgroud)

但它也不起作用。哦,我必须提到,我使用 Bluebird:

var Promise = require('bluebird'),
    mongoose = require('mongoose');

mongoose.Promise = Promise;
Run Code Online (Sandbox Code Playgroud)

不是在处理程序中创建了承诺的重复,但没有从处理程序中返回,这家伙忘记返回承诺。

Ber*_*rgi 5

问题很大程度上在于使用next回调,它调用创建 Promise 的函数而不返回它们。理想情况下,钩子只需要返回承诺而不是接受回调。

您应该能够通过使用来防止警告

.then(function(result) {
    next(null, result);
    return null;
}, function(error) {
    next(error);
    return null;
});
Run Code Online (Sandbox Code Playgroud)