Mongoose and Bluebird Use cases

Source: Internet
Author: User
Tags findone

All calls to Nodejs are almost completely asynchronous, and all IO operations are known by callback functions. If an asynchronous call relies on another asynchronous call, it is possible to fall into the legendary callback hell if there is no promise.

Bluebird implements the transformation of asynchronous callbacks into chained notation, and extends the APIs such as catch, finally, bind, and so on, which can help us focus on the error of each query.

The information about promise and Bluebird found on the internet is basically about principle and theory, this article introduces Bluebird practical use example. In practice, we only use promisify classes and methods that need to be chained, and the code is as follows:

//Introduction of database Operation ModulevarMongoDB = require ("./db") Promise= Require ("Bluebird")    ;varMongoose = require ("Mongoose");varSchema =Mongoose. Schema;//declaring the user schema structurevarUserschema =NewSchema ({user_id:string, password: {type:string,default:""}, Nickname: {type:string,default:""}, Introduction: {type:string,default:""}, Age: {type:string,default:""}, Gender: {type:string,default:""},  });//give the user class an interfacevarUser = Mongoose.model ('User', Userschema);//The user class of Promise and its methodsPromise.promisifyall (User); Promise.promisifyall (User.prototype); Module.exports= User;

In addition, the following use of the same set of the table will need to do the above processing

Use the following methods:

Room.findone ({type:'Pano'})        //. EXEC (). Then (function () {Console.log ('Rooms:', Guest)
Instead of returning the query results in a callback, the query results are passed to the next one. Thenreturnuser.findone ({_id:room.creator}); }). Then (function (user) {Console.log ('the user receives the previous. Then passed variables:', user)}) .Catch(function (e) {//Handling Error }) .finally(function () {//Final Code Execution})

Mongoose and Bluebird Use cases

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.