2017-07-03 81 views
1

我想知道什麼時候使用EXEC或隨後,又有什麼區別正確使用異步函數

​​

或使用EXEC

Schema.findOne({_id:id}).exec().then(function(obj){ 
//do somthing 
}) 
+0

是否使用貓鼬(不要選擇字段,也不需要給exec,因爲已經執行)? – rebe100x

+1

[Mongoose的可能的重複 - 執行函數做什麼?](https://stackoverflow.com/questions/31549857/mongoose-what-does-the-exec-function-do) –

回答

0

一些貓鼬的方法返回查詢,但不執行其他人直接執行。

當僅返回查詢時使用exec()。

'then'在執行後用作promise處理程序。

執行後可以使用'then和catch'或回調。

有一個使用promise和使用回調的例子。

Cat.find({}) 
    .select('name age') // returns a query 
    .exec() // execute query 
    .then((cats) => { 

    }) 
    .catch((err) => { 

    }); 

Cat.find({}) 
    .select('name age') // returns a query 
    .exec((err,cats) => { // execute query and callback 
    if(err){ 

    } else { 

    } 
    }); 

現在,讓我們沒有做出同樣的查詢

Cat.find({}) 
    .then((cats) => { 

    }) 
    .catch((err) => { 

    }); 

Cat.find({}, (err,cats) => { 
    if(err){ 

    } else { 

    } 
    }); 
+0

當然貓是一個示例模型! – jesusgn90