如何使用无极保存多个MongoDB的藏品? [英] How to save multiple mongodb collections using Promise?
本文介绍了如何使用无极保存多个MongoDB的藏品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
异步库
我能保存
使用低于code数据
函数保存(回调){
async.parallel([
功能(CB){
Collection1.collection.insert(collections1,CB);
},
功能(CB){
Collection2.collection.insert(collections2,CB);
},
功能(CB){
Collection3.collection.insert(collections3,CB);
}
],回电话);
}
保存(函数(){
的console.log(参数);
});
我怎么能modifiy 保存
功能,因此它会返回诺
?
保存()
。然后(函数(){
的console.log(成功);
})
.catch(函数(){
的console.log('错误');
})
现在我的问题是,怎样写保存
使用承诺不使用功能异步库
??
功能保存(){
返回新希望(函数(解析,拒绝){
//保存收藏在这里?或任何其他方式???
})
}
解决方案
使用的 Promise.all
在保存
函数,那么你可以使用它作为你期望
功能保存(){
VAR承诺= [
新希望(函数(解析,拒绝){
Collection1.collection.insert(collections1,功能(错了,做){
如果(ERR)
拒绝(ERR);
其他
解决(完成);
});
}),
新希望(函数(解析,拒绝){
Collection2.collection.insert(collections2,功能(错了,做){
如果(ERR)
拒绝(ERR);
其他
解决(完成);
});
}),
新希望(函数(解析,拒绝){
Collection3.collection.insert(collections3,功能(错了,做){
如果(ERR)
拒绝(ERR);
其他
解决(完成);
});
})
];
返回Promise.all(承诺);
}保存()。然后(函数(){
的console.log(成功);
})赶上(函数(){
的console.log('错误');
})
using async library
I can save
data using below code
function save(callback){
async.parallel([
function(cb){
Collection1.collection.insert(collections1,cb);
},
function(cb){
Collection2.collection.insert(collections2,cb);
},
function(cb){
Collection3.collection.insert(collections3,cb);
}
],callback);
}
save(function(){
console.log(arguments);
});
How I can modifiy save
function so it will return promise
?
save()
.then(function(){
console.log('success');
})
.catch(function(){
console.log('error');
})
Now my question is, How to write save
function using promise without using async library
??
function save(){
return new Promise(function(resolve,reject){
//save collections here?? or any other way???
})
}
解决方案
Use Promise.all
inside save
function, then you are able to use it as you expect
function save(){
var promises = [
new Promise(function(resolve, reject) {
Collection1.collection.insert(collections1, function(err, done){
if(err)
reject(err);
else
resolve(done);
});
}),
new Promise(function(resolve, reject) {
Collection2.collection.insert(collections2, function(err, done){
if(err)
reject(err);
else
resolve(done);
});
}),
new Promise(function(resolve, reject) {
Collection3.collection.insert(collections3, function(err, done){
if(err)
reject(err);
else
resolve(done);
});
})
];
return Promise.all(promises);
}
save().then(function(){
console.log('success');
}).catch(function(){
console.log('error');
})
这篇关于如何使用无极保存多个MongoDB的藏品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文