Bluebird - 承诺是在处理程序中创建的,但未从中返回 [英] Bluebird — a promise was created in a handler but was not returned from it
问题描述
首先,我知道我必须返回
承诺以避免此警告。我也尝试按照建议的方式返回 null
在这里的文档。考虑一下这段代码,我在Mongoose的预保存挂钩中使用它,但我在其他地方遇到过这个警告:
First of all, I know that I have to return
promises to avoid this warning. I've also tried returning null
as suggested here in the docs. Consider this piece of code, I'm using it in Mongoose's pre-save hook, but I've experienced this warning in other places:
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
});
我也尝试过(最初)这种方式:
I've also tried (initially) this way:
story.somevar = somevar;
return next(); // <-- this line throws warning
}).catch(next);
但它也不起作用。哦,我必须提一下,我使用Bluebird:
But it doesn't work either. Oh, and I have to mention, that I use Bluebird:
var Promise = require('bluebird'),
mongoose = require('mongoose');
mongoose.Promise = Promise;
不是一个承诺是在一个处理程序中创建的但是没有从它返回,那个人忘了回来一个承诺。
Not a duplicate of A promise was created in a handler but was not returned from it, the guy forgot to return a promise.
推荐答案
问题几乎是使用 next
回调所有,它调用创建promises而不返回它们的函数。理想情况下,钩子只需要返回承诺而不是回调。
The problem is pretty much using a next
callback at all, which calls functions that create promises without returning them. Ideally the hooks just needed to return promises instead of taking callbacks.
您应该能够通过使用
.then(function(result) {
next(null, result);
return null;
}, function(error) {
next(error);
return null;
});
这篇关于Bluebird - 承诺是在处理程序中创建的,但未从中返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!