无法获得蓝鸟承诺和猫鼬的save()在node.js中工作 [英] Unable to get bluebird promise and mongoose's save() to work in node.js
问题描述
有人可以帮我弄清楚如何在Promise中重写以下工作代码吗?我想执行插入查询,然后通过socket.js
Can anyone help me figure out how to rewrite the following working code in promise? I want to execute an insert query and then send the data back to clients via socket.js
var func = require("functions")
var mongoose = require('mongoose');
var mongo_models = require('./database/mongo_model')(mongoose);
var Promise = require("bluebird");
socket.on("submit",function(d){
if(d[0].src !== undefined)
{
var data = func.clear(sanitizer,d),
tab = new mongo_models.Tab({avg:0,post:data});
tab.save(function(err,tw){
io.sockets.in('index').emit("update",tw)
})
}
});
我尝试了以下代码,但是我从console.log(b)
获取了undefined
.显然save()
没有返回任何结果.
承诺:
I have tried the following code but I'm getting undefined
from console.log(b)
. Apparently the save()
isn't returning any result.
Promise:
socket.on("submit",function(d){
if(d[0].src !== undefined)
{
Promise.props({
one: func.clear(sanitizer,d)
}).then(function(a){
return new mongo_models.Tab({avg:0,post:a.one}).save();
}).then(function(b){
console.log(b); // undefined
io.sockets.in('index').emit("update",b)
}).catch(function (error) {
console.log(error);
})
}
});
推荐答案
在Mongoose中,保存是有问题的,因为Promise返回那里的函数的规则是一个例外.
Save is problematic in Mongoose as being an exception to the rule of promise returning functions there.
我强烈建议您使用显示saveAsync
函数的bluebird来使猫鼬成瘾:
I highly recommend that you promisify mongoose using bluebird which exposes a saveAsync
function:
var Promise = require("bluebird");
var func = require("functions")
var mongoose = Promise.promisifyAll(require('mongoose'));
var mongo_models = require('./database/mongo_model')(mongoose);
然后以以下方式返回异步调用:
And then return the async call as:
// Note the suffix
return new mongo_models.Tab({avg:0,post:a.one}).saveAsync();
这篇关于无法获得蓝鸟承诺和猫鼬的save()在node.js中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!