![](/img/trans.png)
[英]Node js, using mongoose with Q promise does not call reject function
[英]mongoose promise and Q promise
[ 我會回答這個問題,但隨時可以添加解決方案或其他可能發生的問題 ]
在一個我們使用q的nodejs項目上大量使用諾言和貓鼬,我發現結合了兩者的一些不直觀的問題。
第一個是貓鼬承諾沒有.fail
或.catch
。
另一個是Model.create返回一個promise,當解析時會使用多個參數調用resolve函數。 如果經過Q,則Q將僅使用第一個參數調用解析。
請隨時添加更多可能出現的問題; 我將回答如何解決這些問題。
因為貓鼬承諾沒有.catch
或.fail
( 請注意q也會從它們的庫中刪除它們 ),所以您不能在以.catch或.fail結尾的aq堆棧上返回失敗的貓鼬承諾,而不會將其轉換為aq先承諾。 這是我的操作方式(在堆棧的其他位置也已回答):
function something(){
return q()//make sure this function returns a promise instead of an unhandled error
.then(function(){
//do some stuff
})
.then(function(){
return someMongoosePromise
.then(function resolve(res){//make sure to return a q promise if this function is called in a stack that has
//.then.then.then(function(){return something();}).fail(...
return q.resolve(res);
},function reject(err){
return q.reject(err);
}
);
});
}
我遇到的第二個問題是Model.create([doc1,doc2])使用多個參數解析了promise,但是在執行qq時,僅使用一個參數調用了resolve:
q()
.then(function(){
return Model.create([doc1,doc2]);
})
.then(function(docs){
docs===doc1;//David Copperfield took doc2
});
該解決方案與第一個解決方案大致相同:
q()
.then(function(){
return Model.create([doc1,doc2])
.then(function(){//let mongoose resolve the promise
var ret=[],i=arguments.length;
while(--i>-1){
ret.push(arguments[i];
}
return q.resolve(ret);
});
})
.then(function(docs){
docs===[doc1,doc2];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.