简体   繁体   中英

When calling exec on a mongoose query is the callback passed to exec equivalent to a then/catch?

    Recipe.findOne({_id: item.recipe_id}).exec((err, recipe) => {
        if (err) { console.error(err); return err; }
        console.log('recipe: ' + recipe);
    })
    });

vs.

    Recipe.findOne({_id: item.recipe_id}).exec().then(function(recipe){
        console.log('recipe: ' + recipe);
    }).catch(function(err){
       console.error(err);
       return err; 
    });

I can't find good documentation on how the callback sent directly to exec operates.

Mongoose queries return a thenable but not a real Promise ; if you supply the callback, it will execute, otherwise it's used to just build the query.
More info: https://mongoosejs.com/docs/queries.html#queries-are-not-promises

When you use .exec() it will return a real Promise .
So, to your question: yes, the behavior in both cases is equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM