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

标签 javascript node.js mongoose promise bluebird

首先,我知道我必须return promises 来避免这个警告。我也尝试按照建议返回 null here in the docs .考虑这段代码,我在 Mongoose 的预保存 Hook 中使用它,但我在其他地方遇到过这个警告:

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
});

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

        story.somevar = somevar;
        return next(); // <-- this line throws warning
    }).catch(next);

但它也不起作用。哦,我不得不提一下,我使用 Bluebird:

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

mongoose.Promise = Promise;

不是 A promise was created in a handler but was not returned from it 的副本, 那家伙忘了还一个 promise 。

最佳答案

问题几乎完全是使用 next 回调,它调用创建 promise 的函数而不返回它们。理想情况下,钩子(Hook)只需要返回 promise 而不是接受回调。

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

.then(function(result) {
    next(null, result);
    return null;
}, function(error) {
    next(error);
    return null;
});

关于javascript - Bluebird — 在处理程序中创建了一个 promise ,但没有从中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37861736/

相关文章:

javascript - 如何使用 Ajv 编译 JSON 架构的子集?

node.js - 尽管文件存在,但出现错误 : ENOENT: no such file or directory,

node.js - 带有 express : Missing PFX or certificate + private key. 的 socket.io 中的 SSL

javascript - 无法读取未定义的属性 'Symbol(Symbol.iterator)'

javascript - 将数组从 JavaScript 传递到 Asp.net Core

javascript - 我在 Vue.js 中创建了一个不起作用的模式组件

javascript - 如何填充嵌套数组引用? Mongoose

node.js - TypeError : callback. apply 不是allowDiskUse之后的函数

javascript - 确定选择器的目标是否已格式化为 slider

node.js - 如何从 Microsoft bot 框架中创建的 html 表单文本框中检索值?