簡體   English   中英

貓鼬承諾和Q承諾

[英]mongoose promise and Q promise

[ 我會回答這個問題,但隨時可以添加解決方案或其他可能發生的問題 ]

在一個我們使用q的nodejs項目上大量使用諾言和貓鼬,我發現結合了兩者的一些不直觀的問題。

第一個是貓鼬承諾沒有.fail.catch

另一個是Model.create返回一個promise,當解析時會使用多個參數調用resolve函數。 如果經過Q,則Q將僅使用第一個參數調用解析。

請隨時添加更多可能出現的問題; 我將回答如何解決這些問題。

您可以簡單地使用Q函數將Mongoose的諾言轉換為“合適的” Q諾言-實際上,這適用於所有可能的實現。

所以就用

Q(someMongoosePromise) .then(…).catch(…);

多個參數是一個不同的問題。 但是,有一個非常簡單的技巧:將它們轉換為數組並進行處理。

Q(Model.create([doc1,doc2]).then(Array)) .spread(function(d1, d2){ … });

(如果Model.create返回單個數字的承諾,則此解決方案不適用)

因為貓鼬承諾沒有.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM