2016-06-16 21 views
2

首先,我知道我必须return承诺避免此警告。我也尝试按照建议的here in the docs返回null。考虑这段代码,我使用它在猫鼬的预存挂钩,但我已经经历了在其他地方这样的警告:蓝鸟 - 一个承诺是在处理程序中创建的,但没有从它返回

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

但它也不起作用。哦,我不得不提,那我用蓝鸟:

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

mongoose.Promise = Promise; 

不是A promise was created in a handler but was not returned from it重复,那家伙忘记返回一个承诺。

+0

[从成功的jQuery AJAX POST蓝鸟未处理的废品(的可能的复制http://stackoverflow.com/questions/33948597/bluebird-unhandled防止警告-rejection-error-from-successful-jquery-ajax-post) – TylerH

回答

3

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

您应该能够通过使用

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

它的工作原理,谢谢。我改变了一下来调用'next(error);'将错误进一步传递给处理程序。我并不完全了解“钩子只是回复承诺而不是回调”,我可以在哪里阅读?我写的越多,Node.js +承诺的代码越少,我理解它:D –

+0

我的意思是猫鼬应该改变它的API,以便钩子可以只是返回一个承诺,而不必调用“下一个”回调。 – Bergi

相关问题