2017-07-03 61 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